Why should E.printStackTrace be removed?

3

I use Try catch as follows:

try{
   //meu código
} catch(Exception E) {
   E.printStackTrace();
}

Using netbeans IDE, it shows a hint, called "Print Stack Trace", when I click on it, it says ("Throwable.printStackTrace should be removed!)

Why this?

Is there a correct way to show errors? I have seen for example

System.err.println(E.getMessage());

or

JOptionPane.showMessageDialog(null,E.getMessage());
    
asked by anonymous 24.06.2016 / 14:27

1 answer

3

In fact some IDEs show this as Warning for two reasons: Or because you are not handling the exception and simply "passing" and another situation for security reasons. If you use some code analysis tool, it will point out that you should not simply do an e.printStackTrace for several reasons, mainly security and another, do this and show in a dialog for the user is lazy: -)

Handle exceptions each in its proper place. Understand how the exception hierarchy works will help you greatly improve your code. At first I always did generic try catch (Exception e). Until one day I said this here is a trick. I decided to study and I learned that throwing the error and not treating it is of no use and I understood how to use exception handling. They serve for you to treat each specific situation in your application. Never give the user a native exception without going through a treatment. I'll give you a simple example:

public class Operacoes {
  public int dividir(Integer numerador, Integer denominador) {
    if (denominador.equals(0)) {
      throw new IllegalArgumentException("Denominador não pode ser zero");
    }
    return numerador/denominador;
  }
}

When using, you could do:

try{
   dividir(10,0);
}catch(IllegalArgumentException ex){
   //como você está tratando propriamente lá no método, poderia ser exibido para o usuário um alerta contendo ex.getMessage();
}

I hope I understand. Any questions, comment and we'll help you. It's a really cool subject.

    
24.06.2016 / 14:30