什么时候
when 是在 C#6 中添加的关键字,用于异常过滤。
在引入 when 关键字之前,你可以为每种类型的异常设置一个 catch 子句; 通过添加关键字,现在可以实现更细粒度的控制。
when 表达式附加到 catch 分支,并且只有当 when 条件为 true 时,才会执行 catch 子句。有几个 catch 子句可能具有相同的异常类类型和不同的 when 条件。
private void CatchException(Action action)
{
try
{
action.Invoke();
}
// exception filter
catch (Exception ex) when (ex.Message.Contains("when"))
{
Console.WriteLine("Caught an exception with when");
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception without when");
}
}
private void Method1() { throw new Exception("message for exception with when"); }
private void Method2() { throw new Exception("message for general exception"); }
CatchException(Method1);
CatchException(Method2);