CA2200:必須重新擲回以保存堆疊詳細資料
屬性 | 值 |
---|---|
規則識別碼 | CA2200 |
標題 | 必須重新擲回以保存堆疊詳細資料 |
類別 | 使用方式 |
修正程式是中斷或非中斷 | 不中斷 |
預設在 .NET 8 中啟用 | 作為警告 |
原因
重新擲回例外狀況,並在 語句中明確指定例外狀況 throw
。
檔案描述
擲回例外狀況後,其所攜帶資訊的一部分是堆疊追蹤。 堆疊追蹤是方法呼叫階層的清單,其開頭為擲回例外狀況的方法,並以攔截例外狀況的方法結尾。 如果在 語句中 throw
指定例外狀況來重新擲回例外狀況,堆疊追蹤會在目前的 方法上重新開機,而且擲回例外狀況的原始方法與目前方法之間的方法呼叫清單會遺失。 若要保留原始堆疊追蹤資訊與例外狀況,請使用 throw
語句而不指定例外狀況。
如果您要從處理常式 ( catch
區塊) 以外的某個位置重新擲回例外狀況,請使用 ExceptionDispatchInfo.Capture(Exception) 來擷取處理常式中的例外狀況,以及 ExceptionDispatchInfo.Throw() 當您想要重新擲回例外狀況時。 如需詳細資訊,請參閱 擷取例外狀況以稍後 重新擲回。
如何修正違規
若要修正此規則的違規,請重新擲回例外狀況,而不明確指定例外狀況。
隱藏警告的時機
請勿隱藏此規則的警告。
範例
下列範例顯示違反規則的方法 CatchAndRethrowExplicitly
和滿足規則的方法 CatchAndRethrowImplicitly
。
class TestsRethrow
{
static void Main2200()
{
TestsRethrow testRethrow = new TestsRethrow();
testRethrow.CatchException();
}
void CatchException()
{
try
{
CatchAndRethrowExplicitly();
}
catch (ArithmeticException e)
{
Console.WriteLine("Explicitly specified:{0}{1}",
Environment.NewLine, e.StackTrace);
}
try
{
CatchAndRethrowImplicitly();
}
catch (ArithmeticException e)
{
Console.WriteLine("{0}Implicitly specified:{0}{1}",
Environment.NewLine, e.StackTrace);
}
}
void CatchAndRethrowExplicitly()
{
try
{
ThrowException();
}
catch (ArithmeticException e)
{
// Violates the rule.
throw e;
}
}
void CatchAndRethrowImplicitly()
{
try
{
ThrowException();
}
catch (ArithmeticException)
{
// Satisfies the rule.
throw;
}
}
void ThrowException()
{
throw new ArithmeticException("illegal expression");
}
}
Imports System
Namespace ca2200
Class TestsRethrow
Shared Sub Main2200()
Dim testRethrow As New TestsRethrow()
testRethrow.CatchException()
End Sub
Sub CatchException()
Try
CatchAndRethrowExplicitly()
Catch e As ArithmeticException
Console.WriteLine("Explicitly specified:{0}{1}",
Environment.NewLine, e.StackTrace)
End Try
Try
CatchAndRethrowImplicitly()
Catch e As ArithmeticException
Console.WriteLine("{0}Implicitly specified:{0}{1}",
Environment.NewLine, e.StackTrace)
End Try
End Sub
Sub CatchAndRethrowExplicitly()
Try
ThrowException()
Catch e As ArithmeticException
' Violates the rule.
Throw e
End Try
End Sub
Sub CatchAndRethrowImplicitly()
Try
ThrowException()
Catch e As ArithmeticException
' Satisfies the rule.
Throw
End Try
End Sub
Sub ThrowException()
Throw New ArithmeticException("illegal expression")
End Sub
End Class
End Namespace
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應