我想知道是否有能力在運算式 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
}
}
代碼將以以下錯誤結束:
重新拋出捕獲的例外更改堆疊資訊
此代碼僅用于示例目的;很明顯,陳述句 switch case 是顯而易見的解決方案
switch (ex)
{
case 1: ...
case 2: ...
default: throw;
{
uj5u.com熱心網友回復:
只需捕獲特定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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/411181.html
標籤:
上一篇:Blazor未處理的例外:無法為型別“BlazorStrap.BSCarousel”的屬性“BlazorStrapSrc”提供值
