我有这样的东西:
catch (Exception ex)
{
if (ex is "Exception Type")
{
}
else if (ex is SqlException)
{
}
else if
{
...
...
...
}
C#
中的权利是这样吗,is
到底是什么意思,这是它的作用还是另一种方式?
try {
// Do something
}
catch(SqlException ex) {
}
catch(AnotherException ex) {
}
然后,从最具体的异常开始并逐步发展为一般异常非常重要。
try
{
}
catch (SqlException ex)
{
...
}
catch(AnotherExceptionType ex)
{
...
}
您可以在try
块之后添加任意多。
try
{
return DoStuff();
}
catch (InvalidOperationException opEx)
{
return HandleInvalidOp(opEx);
}
catch (DivideByZeroException divEx)
{
return HandleDivException(divEx);
}
catch (Exception ex) // final catch-all
{
return HandleEx(ex);
}
使用模式匹配开关:
try { return DoStuff(); } catch (Exception ex) { switch (ex) { case InvalidOperationException opEx: return HandleInvalidOp(opEx); case DivideByZeroException divEx: return HandleDivException(divEx); default: return HandleEx(ex); } }