[英]C# Exception Handling - will last catch block fetch re-thrown Exception?
我想知道這段代碼是否可以在 10 次重試后調用CleanUp()
的方式工作? 或者throw new Exception()
不會被最后一個 catch 塊捕獲?
public void Process()
{
try
{}
catch (MyException e)
{
int retries = GetRetries();
if(retries > 10)
{
_logger.LogError("Retried event already {retries} times. Giving up.", retries);
throw new Exception("Giving up!");
}
Process();
}
catch (Exception e)
{
CleanUp();
}
}
不,它不是那樣工作的。 對於任何給定的try
/ catch
塊,只有源於try
的異常才能被相應的catch
塊catch
。 在catch
塊中拋出的異常不能被同一級別的其他catch
塊catch
。
finally
塊允許您在控件因任何原因離開try
/ catch
時運行代碼。 因此,如果您的try
結束時已經有了CleanUp
那么您只需將最終catch(Exception e)
更改為finally
並在try
部分的末尾刪除CleanUp
。
但是,如果您只想在控制通過異常離開try
/ catch
時運行CleanUp
,那么您就沒有那么幸運了。 IL 中有一個fault
子句,它是finally
,但僅用於異常,但在 C# 中沒有公開。
因此,如果您需bool
,通常最好引入一個額外的bool
指示您無一例外地到達了try
塊的末尾,並使用它使您的CleanUp
調用在finally
有條件。
或者你可以通過嵌套try
/ catch
塊來模擬try
/ catch
/ fault
:
try
{
try
{}
catch (MyException e)
{
int retries = GetRetries();
if(retries > 10)
{
_logger.LogError("Retried event already {retries} times. Giving up.", retries);
throw new Exception("Giving up!");
}
Process();
}
}
catch
{
//Act as fault
CleanUp();
throw;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.