我可以在表达式切换案例中重新抛出现有异常吗?
Can I rethrow an existing exception in an expression switch case?
我想知道是否可以在表达式转换案例中重新抛出现有异常(在 catch 子句中)?请看一下代码示例:
try
{
// Some code...
}
catch (Exception ex)
{
return ex switch
{
ExceptionA => // return some value with expression.
ExceptionB => // return some value with expression
_ => throw ex
}
}
代码将以以下错误结束:
Re-throwing caught exception changes stack information
此代码仅供参考;很明显,声明 switch case 是显而易见的解决方案
switch (ex)
{
case 1: ...
case 2: ...
default: throw;
{
只需捕获特定的 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
}
正如您询问如何使用 switch
执行此操作一样,这也应该有效:
try
{
// Some code...
}
catch (Exception ex)
{
switch(ex)
{
case ExceptionA exA:
return "something";
case ExceptionA exA:
return "something else";
default:
throw;
}
}
我想知道是否可以在表达式转换案例中重新抛出现有异常(在 catch 子句中)?请看一下代码示例:
try
{
// Some code...
}
catch (Exception ex)
{
return ex switch
{
ExceptionA => // return some value with expression.
ExceptionB => // return some value with expression
_ => throw ex
}
}
代码将以以下错误结束:
Re-throwing caught exception changes stack information
此代码仅供参考;很明显,声明 switch case 是显而易见的解决方案
switch (ex)
{
case 1: ...
case 2: ...
default: throw;
{
只需捕获特定的 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
}
正如您询问如何使用 switch
执行此操作一样,这也应该有效:
try
{
// Some code...
}
catch (Exception ex)
{
switch(ex)
{
case ExceptionA exA:
return "something";
case ExceptionA exA:
return "something else";
default:
throw;
}
}