Why should E.printStackTrace be removed?

Asked

Viewed 1,249 times

3

Use Try catch as follows:

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

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

Because that?

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

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

or

JOptionPane.showMessageDialog(null,E.getMessage());

1 answer

3


In fact some Ides show this as Warning for two reasons: Or because you are not treating the exception and simply "going over" and other 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 other, do this and show in a dialog for the user is laziness :-)

Treat each exception in its proper place. Understand how the exception hierarchy works this will help you greatly improve your code. At first I always made Catch Ry(Exception and) generic. Until one day I said it here is a mess. I decided to study and learned that throwing the error and not treating it does not help anything and I understood how to use exception treatment. They serve to treat each specific situation in your application. Never show 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 have understood. Any questions, comment and we will help you. It is a very cool subject.

  • So, I do the error handling, showing the user some message or something like that when it gives certain errors, but even so, I like to put for example E.printstackTrace(); //for me to know what happened Joptionpane.showMessageDialog(null,"Some Error Message"); but still, I find it strange that the Ides ask to remove stackTrace

Browser other questions tagged

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