[英]Dotnet 6, Rethrow Existing Exception in Expression Switch Case
I'm wondering if there any capability to rethrow existing exception (in catch clause), within expression switch case, please take a look on the code example:我想知道在表达式 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
}
}
The following code will end with the following error: Re-throwing caught exception changes stack informatio
以下代码将以以下错误结束:
Re-throwing caught exception changes stack informatio
Edit : This code is for example purposes, clearly that solving it with statement switch case is the obvious solution编辑:此代码仅用于示例目的,显然用语句 switch case 解决它是明显的解决方案
switch (ex)
{
case 1: ...
case 2: ...
default: throw;
{
Just catch the specific Exception
type:只需捕获特定的
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
}
As you have asked how to do this with the switch
, this should work as well:正如您询问如何使用
switch
执行此操作一样,这也应该有效:
try
{
// Some code...
}
catch (Exception ex)
{
switch(ex)
{
case ExceptionA exA:
return "something";
case ExceptionA exA:
return "something else";
default:
throw;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.