加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c#使用try-catch捕获异常的最佳实践?

发布时间:2020-12-15 23:46:54 所属栏目:百科 来源:网络整理
导读:假设我需要运行methodA,而methodA将抛出FormatException. 如果我写这个块: try{ methodA();}catch (Exception ex){ methodB();}catch (FormatException ex){ methodC();} 它是否会运行methodC,知道FormatException也是一个Exception,因此将进入methodB的cat
假设我需要运行methodA,而methodA将抛出FormatException.

如果我写这个块:

try
{
    methodA();
}
catch (Exception ex)
{
    methodB();
}
catch (FormatException ex)
{
    methodC();
}

它是否会运行methodC,知道FormatException也是一个Exception,因此将进入methodB的catchblock.

或者这样写它更好:

try
{
    methodA();
}
catch (Exception ex)
{
    if(ex is FormatException)
    {
        methodC();
    } else
    {
        methodB();
    }
}

解决方法

不,它不会运行methodC,但是如果你交换了catch的顺序,它会:

try
{
    methodA();
}
catch (FormatException ex)
{
    methodC();    
}
catch (Exception ex)
{
    methodB();
}

引用MSDN:

It is possible to use more than one specific catch clause in the same try-catch statement. In this case,the order of the catch clauses is important because the catch clauses are examined in order. Catch the more specific exceptions before the less specific ones. The compiler produces an error if you order your catch blocks so that a later block can never be reached.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读