[英]How to check the types of Exceptions thrown in a catch block?
I have something like this:我有这样的事情:
catch (Exception ex)
{
if (ex is "Exception Type")
{
}
else if (ex is SqlException)
{
}
else if
{
...
...
...
}
Is this right in C#
and what does the is
mean anyway, which is its role or is there another way?这在
C#
中是否正确,无论如何,这is
什么意思,这是它的作用还是有其他方式?
Yes, there is another way.是的,还有另一种方法。 By calling the specific exceptions that could possibly occur when running a block of code:
通过调用运行代码块时可能发生的特定异常:
try {
// Do something
}
catch(SqlException ex) {
}
catch(AnotherException ex) {
}
Then it is very important to start with the most specific exception and work your way towards a general exception.然后从最具体的例外开始并朝着一般例外努力是非常重要的。
Multiple catch blocks is an answer( docs ):多个 catch 块是一个答案( 文档):
try
{
}
catch (SqlException ex)
{
...
}
catch(AnotherExceptionType ex)
{
...
}
you can add as many as you like after your try
block.您可以在
try
块之后添加任意数量的内容。
UPD As added in comments to this answer - order is important, so if you have exceptions hierarchy catch derived ones first. UPD正如在此答案的评论中添加的那样 - 顺序很重要,因此如果您有异常层次结构,请先捕获派生的。
Classic option:经典选项:
try
{
return DoStuff();
}
catch (InvalidOperationException opEx)
{
return HandleInvalidOp(opEx);
}
catch (DivideByZeroException divEx)
{
return HandleDivException(divEx);
}
catch (Exception ex) // final catch-all
{
return HandleEx(ex);
}
Using pattern matching switch:使用模式匹配开关:
try
{
return DoStuff();
}
catch (Exception ex)
{
switch (ex)
{
case InvalidOperationException opEx:
return HandleInvalidOp(opEx);
case DivideByZeroException divEx:
return HandleDivException(divEx);
default:
return HandleEx(ex);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.