Reputation: 1731
In msdn link, it is mentioned that
Do not throw System.Exception or System.SystemException.
In my code i am throwing like this
private MsgShortCode GetshortMsgCode(string str)
{
switch (str.Replace(" ","").ToUpper())
{
case "QNXC00":
return MsgShortCode.QNXC00;
default:
throw new Exception("Invalid message code received");
}
}
is this a bad practice??
Upvotes: 5
Views: 220
Reputation: 5452
I'm reluctant to use terms like "bad practice" because almost everything is correct in some contexts. But usually, yes, it's considered better to throw the most specific kind of exception that exists for your situation, and if a specific one doesn't exist you should define one.
The reason is that if you throw Exception
, your callers can't distinguish between the error you're raising and any other exception that may have been thrown by the system during the call they made to your code.
In many cases the caller might decide to handle your exception differently than other problems, or at least they might log a specific message knowing that your exception occurred. That would be difficult for the caller to achieve if your exception can't easily be distinguished from others.
Upvotes: 1
Reputation: 8488
In this specific instance you should be throwing ArgumentException
.
The main point of specific exception types is to think about it from the callers perspective. I understand this is actually quite tricky when you are also writing the calling code too as you understand the implementation details on both sides. However, always try and think about how you can provide the caller with enough information to clearly understand what if anything they did wrong.
In this instance simply throwing Exception
would mean they would have to parse the error message to understand what they did wrong whereas throwing ArgumentException
means they can more easily differentiate in their try/catch between them having passed you something invalid or you having failed to executed correctly for some other reason.
Upvotes: 3
Reputation: 7105
Generally you can be more explicit.
In this case, you can throw a
ArgumentException
The more specific you are, the easier it is for other code to handle the exception.
This allows you to do
try
{
GetshortMsgCode("arg")
}
catch(ArgumentException e)
{
//something specific to handle bad args, while ignoring other exceptions
}
Upvotes: 9