Using e.printStackTrace () in Java

This is probably a beginners question, but hope you can help me. :) I have something like this:

try { //try to do something there } catch (IOException e) { //handle the exception e.printStackTrace(); } 

I am using NetBeans IDE and for some reason printStackTrace is underlined in squiggly line. When I press Alt + Enter, it says that Throwable.printStackTrace () should be deleted. What does it mean? Can anyone give more insight into what this can mean? Or can I ignore this?

Thank!

+50
java ioexception
Aug 18 2018-11-11T00:
source share
5 answers

This is just a recommendation. In eclipse, everything is fine - I believe that only the IDE tells you that there are more conventional methods for doing it, as well as some other answers. I believe that this is useful for debugging and that you should tell users when a fatal error occurs, use the debugging mode (for example, the -d console switch) to collect these logs.

+19
Aug 18 2018-11-11T00:
source share

Try:

 e.printStackTrace(System.out); 
+35
Aug 18 2018-11-11T00:
source share

Probably because printStackTrace() does not cope with the error as much as just dumping the stack in the console. It acts like a placeholder until you replace it with the correct error handling (if necessary) and replace the output with some kind of logger.

+14
Aug 18 2018-11-11T00:
source share

e.printStackTrace ();

This is not a good practice, because it prints in the standard ErrorStream, which in most cases is a console!

NetBeans should warn you about this. Good practice with this is to post a message. Follow the same link:

http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html

EDIT See First Comment below for more information.

+9
Aug 18 2018-11-11T00:
source share

Just printing a stack trace is not enough. Printing an exception stack trace does not in itself mean that this is a completely wrong practice, but printing only a stack trace when an exception occurs is a problem.

Always log exceptions (using a good logging structure ), but do not expose them to the end user. And make sure to show the stack trace only in design mode.

I myself use (most of the time) logger.log(Level.SEVERE, <exception>.getMessage(), <exception>); .

when netbeans offer you to handle the exception " Surround Statement with try-catch ", if you click on it, it will throw):

 try { //something need to be handle(exception that throw) } catch (SQLException ex) { Logger.getLogger(ClassName.class.getName()).log(Level.SEVERE, null, ex); } 

This is better than ex.printStackTrace(); .

This can help:

+1
Aug 6 '17 at 9:37 on
source share



All Articles