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;
}
}
}
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);
And show it to the user in catch block like:
Console.WriteLn(ex.Message);
I've seen this approach recommended by an MVP. What are the benefits of this approach over the followings:
WebServiceException
class, AuthenticationException
class, etc.) Here's the link to the recommendation by the MVP.
Thank you.
Personally, i don't think it's a good idea.
You should always throw as specific exceptions as possible. The same goes for catching.
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?