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??
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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With