问题描述
有哪些优点和如下实施自定义异常的缺点:
创建一个枚举类型,再在其说明presents错误信息:
What are the pros and cons of implementing a custom exception as follows:
Create an enum which represents error messages in its descriptions:
public class Enums
{
public enum Errors
{
[Description("This is a test exception")]
TestError,
...
}
}
创建一个自定义异常类:
Create a custom exception class:
public class CustomException : ApplicationException
{
protected Enums.Errors _customError;
public CustomException(Enums.Errors customError)
{
this._customError = customError;
}
public override string Message
{
get
{
return this._customError!= Enums.Errors.Base ? this.customError.GetDescription() : base.Message;
}
}
}
在 GetDescription
的方法是使用反射它获取枚举描述枚举扩展方法。这样一来,我可以抛出异常,如:
The GetDescription
method is an enum extension method which gets the enum description using reflection. This way, I can throw exception like:
throw new customException(enums.Errors.TestError);
和它显示给用户像catch块:
And show it to the user in catch block like:
Console.WriteLn(ex.Message);
我见过的建议MVP的这种做法。什么是这种方法在以下的好处:
I've seen this approach recommended by an MVP. What are the benefits of this approach over the followings:
- 在使用通用的异常:抛出新的异常(错误信息);.
- 使用自定义异常:定义自定义异常的任何情况。例如(
WebServiceException
类,的AuthenticationException
类等)
- Using generic exception: throw new Exception("Error Message");.
- Using Custom Exception: Define custom exceptions for any situation. e.g. (
WebServiceException
class,AuthenticationException
class, etc.)
这里的链接由MVP的建议。
感谢你。
推荐答案
就个人而言,我不认为这是一个好主意。
Personally, i don't think it's a good idea.
您应该总是抛出的特殊例外情况越好。这同样适用于捕捉。
You should always throw as specific exceptions as possible. The same goes for catching.
这很容易决定,如果我们要赶 WebServiceException
或的AuthenticationException
,但你的枚举,例如,我们必须分析字符串来决定,如果我们要赶与否。如果这条消息的变化,会发生什么?
It's easy to decide if we want to catch a WebServiceException
or AuthenticationException
, but with your Enum-example, we have to parse a string to decide if we want to catch it or not. What happens if this message changes?
我不认为这有什么好处可言。对于每一个错误类型,你必须创建一个新的枚举成员。为什么不创建一个新的类呢?
I don't think it has any benefits at all. For each error type, you have to create a new Enum member. Why not create a new class instead?
这篇关于实现一个通用的自定义异常的优点和缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!