我可以在表达式 switch 情况下重新抛出现有异常吗?

ofi*_*amo 1 c# asp.net .net-6.0

我想知道是否有能力在表达式 switch 情况下重新抛出现有异常(在 catch 子句中)?请看一下代码示例:

try 
{
    // Some code...
}
catch (Exception ex)
{
  return ex switch
  {
    ExceptionA => // return some value with expression.
    ExceptionB => // return some value with expression
    _ => throw ex
  }

}
Run Code Online (Sandbox Code Playgroud)

该代码将以以下错误结束:

重新抛出捕获的异常会更改堆栈信息

该代码仅供示例之用;很明显,语句 switch case 是显而易见的解决方案

switch (ex)
{
  case 1: ...
  case 2: ...
  default: throw;
{
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 6

只要抓住具体Exception类型:

try
{
    // Some code...
}
catch (ExceptionA exA)
{ 
    // maybe log this
    return "something"; 
}
catch (ExceptionB exB)
{ 
    // maybe log this
    return "something else"; 
}
catch (Exception ex)
{ 
    // log this
    throw; // throw keeps the original stacktrace as opposed to throw ex 
}
Run Code Online (Sandbox Code Playgroud)

正如您询问如何使用 执行此操作switch,这也应该有效:

try
{
    // Some code...
}
catch (Exception ex)
{
    switch(ex)
    {
        case ExceptionA exA:
            return "something";
        case ExceptionA exA:
            return "something else";
        default:
            throw;
    }
}
Run Code Online (Sandbox Code Playgroud)