我们可以在C#中使用多个catch块吗? [英] Can we use multiple catch blocks in C#?

查看:292
本文介绍了我们可以在C#中使用多个catch块吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用多个捕获块吗?



我尝试过:



班学生

{

试试{

...

}

catch(例外情况)

{

}

catch(例外情况)

{

}

终于()

{

}



}

Can use Multiple catch blocks?

What I have tried:

class student
{
try{
...
}
catch (Exception ex)
{
}
catch (Exception s)
{
}
finally()
{
}

}

推荐答案

是的,当然你可以在C#中拥有多个catch块。从C#6开始,你现在有了异常过滤器(VB.NET已经有这么长时间了)。请参阅此处的语句级功能部分:[ ^ ]。



我强烈建议您研究MS的这些异常处理指南:[ ^ ]。



F-ES Sitecore在这里向您展示了一个很好的例子,但是我认为这个例子的一个特征并不是一个好的做法:拥有一个通用的全能那将会吞噬你没有捕获的任何异常类型。



imho,良好做法要求你至少登录你吞下的错误。并且,imho,最好的做法是永不吞咽,但如果你必须使用全能,则重新抛出。
Yes, of course you can have multiple catch blocks in C#. As of C#6 you now have exception filters (VB.NET has had these a long time). See the section "Statement-level features" here: [^].

I strongly suggest you study these Exception handling guidelines from MS: [^].

F-ES Sitecore showed you a good example here, but there's one "feature" of that example I think is not good practice: having a "generic catch-all" that is going to "swallow" any Exception type you did not catch.

imho, good practice demands that you at least log an error that you "swallow." And, imho, best practice is to "never swallow," but re-throw if you must use a "catch-all."


如果你想使用多个catch块,那么异常类型必须是不同的



If you want to use multiple catch blocks the exception type must be different

catch (ExceptionType1 a)
{
}
catch (ExceptionType2 b)
{
}
catch (ApplicationException c)
{
}
catch (Exception d)
{
}





当抛出异常时,它将检查异常是否为ExceptionType1类型,如果不是,它将转到下一个catch,依此类推列表,直到找到匹配的类型。



When an exception is thrown it will check if the exception is type ExceptionType1, and if not it will go to the next catch and so on down the list until if finds a matching type.


这篇关于我们可以在C#中使用多个catch块吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆