Keep stack trace when method rethrows the captured exception

1

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

  

CA2200 Rethrow to preserve stack   details 'fooBLO.FooMethod (DataProjectDTO, 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 PreencherGeracao method and the CadastrarSolicitacao that are called by it already have a throw and in the example method _interfaceDAO.CadastrarSolicitacao it has the possibility to give another% with% being that this may have been sent from one of the methods called by it, and thus lose the trace.

Code Analysis itself directs you to use only throw without the argument. Is this really the best practice?

The argument I am still using to write the system error log. I am aware that this often causes the write of more than one log error, because if the method throw com% it will write a log and method example as well. Is that a bad practice? Should I write the log only on the last layer?

    
asked by anonymous 19.02.2018 / 15:57

1 answer

1

Yes it is better to use throw than throw e because it does not destroy the stack trace and gives better information about the error, but maybe the correct one is not even having this try-catch .

If you need to log in any error without doing anything else, nothing specific, this should be done in another location. If you are going to do something specific it is there that you should logar . Almost always catch Exception is an error , including this case.

You may be using exception where you should not . Maybe this is the case for another solution . And see more and also .

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

    
19.02.2018 / 16:13