Keep stack trace when the method gives rethrow in the captured Exception

Asked

Viewed 68 times

1

I ran the Visual Studio Code Analysis application and in several methods received the following message:

CA2200 Rethrow to preserve stack Details 'fooBLO.Foomethod(Dadosprojectdto, string)' rethrows a Caught Exception and specifies it explicitly as an argument. Use throw without an argument Instead, in order to preserve the stack Location Where the Exception was initially Raised. BLL Fooblo.Cs 143

Example method:

public bool CadastrarSolicitacao(DadosProjeto oDadosProjeto, string tipoProcesso)
{
    try
    {
        //Método que também utiliza Exception causando o "rethrows"
        GeraSolicitacao solicitacao = PreencherGeracao(oDadosProjeto);

        //Outras tratativas do método......
        //..........

        //Método que também utiliza Exception causando o "rethrows"
        return _interfaceDAO.CadastrarSolicitacao(solicitacao);
    }
    catch (Exception e)
    {
        //Aqui utilizo o exception em "e" para gravar o log do erro (e.Message)
        throw e;
    }
}

I understood that in this method I get the alert because both the method PreencherGeracao as to the CadastrarSolicitacao who are called by him already has a throw and in the example method _interfaceDAO.CadastrarSolicitacao he has the possibility to give another throw this being that this may have been sent from one of the method called by him, and thus lose the tracking.

Code Analysis itself guides you to use only the throw without the argument. That’s really best practice?

The argument I am still using to record the system error log. I am aware that this often causes saving more than one log error because the method PreencherGeracao der Exception he will record a log and the example method as well. Is this a bad practice? I should record the log only in the last layer?

1 answer

1


Yes it is better to use throw than throw e because it doesn’t destroy the stack trace and gives better information about the error, but maybe the right thing is not to have this try-catch.

If you need log in every mistake without doing anything else, nothing specific, this should be done elsewhere. If you are going to do something specific it is there that you should log in. Almost always capture Exception is a mistake, including this case.

Maybe I’m using exception where it should not. Perhaps it is the case of another solution. And see more and also.

Read What is the difference between "throw" and "throw ex"?. Maybe it’s duplicate, I just saw it at the end.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.