Partilhar via


CA2200: Relançar para preservar os detalhes da pilha

Property valor
ID da regra CA2200
Título Relançar para preservar os detalhes da pilha
Categoria Utilização
A correção está quebrando ou não quebrando Sem quebra
Habilitado por padrão no .NET 8 Como aviso

Motivo

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

Descrição da regra

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

Se você estiver relançando a exceção de algum lugar diferente do manipulador (catch bloco ), 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 sem especificar a exceção explicitamente.

Quando suprimir avisos

Não suprima um aviso desta 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 TestsRethrow();
        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

Consulte também