| 속성 | 값 |
|---|---|
| 규칙 ID | CA2200 |
| 제목 | 스택 정보를 유지하도록 다시 throw하십시오. |
| 범주 | 사용 현황 |
| 수정 사항이 호환성을 깨뜨리는지 여부 또는 무중단인지 여부 | 주요 변경 아님 |
| .NET 10에서 기본적으로 사용하도록 설정 | 경고로서 |
| 적용 가능한 언어 | C# 및 Visual Basic |
원인
예외가 다시 던져지며 throw 문에 예외가 명시적으로 지정되어 있습니다.
규칙 설명
예외가 throw되는 경우 전달되는 정보의 일부는 스택 추적입니다. 스택 추적은 예외를 throw하는 메서드로 시작되고 예외를 catch하는 메서드로 종료되는 메서드 호출 계층 구조의 목록입니다. 문에서 예외를 지정하여 예외를 다시 throw하면 현재 메서드에서 throw 스택 추적이 다시 시작되고 예외를 throw한 원래 메서드와 현재 메서드 간의 메서드 호출 목록이 손실됩니다. 예외에서 원래 스택 추적 정보를 유지하려면 예외를 지정하지 않고 throw 문을 사용합니다.
처리기가 아닌 다른 곳에서 예외를 rethrow하는 경우(catch 블록), 처리기에서 예외를 캡처할 때는 ExceptionDispatchInfo.Capture(Exception)을(를) 사용하고 rethrow하고 싶을 때는 ExceptionDispatchInfo.Throw()을(를) 사용합니다.
자세한 내용은 예외를 올바르게 캡처하고 재투척하는 방법을 참조하세요.
위반 문제를 해결하는 방법
이 규칙 위반을 해결하려면 예외를 명시적으로 지정하지 않고 다시 던지세요.
경고를 표시하지 않는 경우
이 규칙에서 경고를 무시하지 마십시오.
예시
다음 예제에서는 규칙을 위반하는 메서드 CatchAndRethrowExplicitly와 규칙을 충족하는 메서드 CatchAndRethrowImplicitly를 보여 줍니다.
class TestsRethrow
{
static void Main2200()
{
TestsRethrow testRethrow = new();
testRethrow.CatchException();
}
void CatchException()
{
try
{
CatchAndRethrowExplicitly();
}
catch (ArithmeticException e)
{
Console.WriteLine($"Explicitly specified:{Environment.NewLine}{e.StackTrace}");
}
try
{
CatchAndRethrowImplicitly();
}
catch (ArithmeticException e)
{
Console.WriteLine($"{Environment.NewLine}Implicitly specified:{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
참고하기
.NET