Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for Catching and throwing the exception

Tags:

c#

exception

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??

like image 556
Olivarsham Avatar asked Nov 27 '12 13:11

Olivarsham


Video Answer


2 Answers

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
}
like image 146
Erix Avatar answered Nov 03 '22 01:11

Erix


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.

like image 22
Darren Lewis Avatar answered Nov 02 '22 23:11

Darren Lewis