[英]How to throw exception to next catch?
我想在下一次捕獲時拋出異常,(我附上了圖片)
有人知道怎么做嗎?
C# 6.0
來救援!
try
{
}
catch (Exception ex) when (tried < 5)
{
}
你不能,並且試圖這樣做表明你的catch
塊中有太多的邏輯,或者你應該重構你的方法只做一件事。 如果你不能重新設計它,你將不得不嵌套你的try
塊:
try
{
try
{
...
}
catch (Advantage.Data.Provider.AdsException)
{
if (...)
{
throw; // Throws to the *containing* catch block
}
}
}
catch (Exception e)
{
...
}
另一方面,從 C# 6 開始,有異常過濾器,因此您可以在實際捕獲異常之前檢查條件:
try
{
...
}
catch (Advantage.Data.Provider.AdsException) when (tries < 5)
{
tries++;
// etc
}
// This will catch any exception which isn't an AdsException *or* if
// if the condition in the filter isn't met.
catch (Exception e)
{
...
}
一種可能性是嵌套 try/catch 子句:
try
{
try
{
/* ... */
}
catch(Advantage.Data.Provider.AdsException ex)
{
/* specific handling */
throw;
}
}
catch(Exception ex)
{
/* common handling */
}
還有另一種方法 - 僅使用您的一般 catch 語句並自己檢查異常類型:
try
{
/* ... */
}
catch(Exception ex)
{
if(ex is Advantage.Data.Provider.AdsException)
{
/* specific handling */
}
/* common handling */
}
這個答案的靈感來自Honza Brestan 的回答:
}
catch (Exception e)
{
bool isAdsExc = e is Advantage.Data.Provider.AdsException;
if (isAdsExc)
{
tried++;
System.Threading.Thread.Sleep(1000);
}
if (tried > 5 || !isAdsExc)
{
txn.Rollback();
log.Error(" ...
...
}
}
finally
{
將兩個try
塊嵌套在彼此內部是很難看的。
如果您需要使用AdsException
的屬性,請使用as
cast 而不是is
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.