Compartilhar via


CA2200: Relançar para preservar detalhes da pilha

Propriedade Valor
ID da regra CA2200
Título Relançar para preservar detalhes da pilha
Categoria Usage
Correção interruptiva ou sem interrupção Inquebrável
Habilitado por padrão no .NET 10 Como aviso
Idiomas aplicáveis C# e Visual Basic

Causa

Uma exceção é lançada novamente e a exceção é especificada explicitamente na instrução throw.

Descrição da regra

Quando uma exceção é lançada, parte das informações que ela carrega consistem no rastreamento de pilha. O stack trace é uma lista da hierarquia de chamadas de método que começa com o método que lança a exceção e termina com o método que a captura. Se uma exceção for relançada especificando a exceção na instrução throw, o rastreamento de pilha é reiniciado no método atual, e a lista das chamadas de métodos entre o método original que lançou a exceção e o método atual é perdida. Para manter as informações de rastreamento de pilha originais com a exceção, use a instrução throw sem especificar a exceção.

Se você estiver relançando a exceção de um local diferente do manipulador (bloco catch), use ExceptionDispatchInfo.Capture(Exception) para capturar a exceção no manipulador e ExceptionDispatchInfo.Throw() quando quiser relançá-la.

Para obter mais informações, consulte Capturar e relançar exceções corretamente.

Como corrigir violações

Para corrigir uma violação dessa regra, relance a exceção sem especificá-la explicitamente.

Quando suprimir avisos

Não suprima um aviso nessa regra.

Exemplo

O exemplo a seguir mostra um método, CatchAndRethrowExplicitly, que viola a regra e um método, CatchAndRethrowImplicitly, que satisfaz a regra.

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

Confira também