我遇到了C#中的这一新功能,该功能允许在满足特定条件时执行catch处理程序。
int i = 0;
try
{
throw new ArgumentNullException(nameof(i));
}
catch (ArgumentNullException e)
when (i == 1)
{
Console.WriteLine("Caught Argument Null Exception");
}
我试图了解何时可能有用。
一种情况可能是这样的:
try
{
DatabaseUpdate()
}
catch (SQLException e)
when (driver == "MySQL")
{
//MySQL specific error handling and wrapping up the exception
}
catch (SQLException e)
when (driver == "Oracle")
{
//Oracle specific error handling and wrapping up of exception
}
..
但这又是我可以在同一处理程序中执行的操作,并根据驱动程序的类型委托给不同的方法。这会使代码更容易理解吗?可以说不是。
我能想到的另一种情况是:
try
{
SomeOperation();
}
catch(SomeException e)
when (Condition == true)
{
//some specific error handling that this layer can handle
}
catch (Exception e) //catchall
{
throw;
}
同样,这是我可以做的事情:
try
{
SomeOperation();
}
catch(SomeException e)
{
if (condition == true)
{
//some specific error handling that this layer can handle
}
else
throw;
}
与处理程序中的特定用例相比,使用“捕获时”功能是否会因为处理程序被跳过而使异常处理更快,并且堆栈展开可能比处理程序中的特定用例早得多?是否有任何更适合此功能的特定用例,然后人们可以采纳这些用例作为良好实践?
try..catch...catch..catch..finally
怎么办?
catch (Exception ex)
检查类型,throw
否则进行检查。稍微更有条理的代码(也就是避免代码杂音)正是此功能存在的原因。(实际上,很多功能都是这样。)
when
需要访问异常本身,这很有用