捕获和抛出异常的最佳实践

Oli*_*ham 5 c# exception

在msdn 链接中,提到
不要抛出System.Exception或System.SystemException.
在我的代码中,我是这样扔的

private MsgShortCode GetshortMsgCode(string str)
        {
            switch (str.Replace(" ","").ToUpper())
            {
                case "QNXC00":
                    return MsgShortCode.QNXC00;
                default:
                    throw new Exception("Invalid message code received");
            }
        }  
Run Code Online (Sandbox Code Playgroud)

这是一个不好的做法?

Eri*_*rix 9

一般来说,你可以更明确.

在这种情况下,你可以扔一个

ArgumentException
Run Code Online (Sandbox Code Playgroud)

您越具体,其他代码处理异常就越容易.

这可以让你做到

try
{
    GetshortMsgCode("arg")
}
catch(ArgumentException e)
{
    //something specific to handle bad args, while ignoring other exceptions
}
Run Code Online (Sandbox Code Playgroud)