Using e.printStackTrace() in Java - java

This is probably a newbie 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 the printStackTrace is underlined in a squiggly line. When I press Alt+Enter, it says Throwable.printStackTrace() should be removed. What does this mean? Could anyone give more insight as what this may mean? Or can I ignore this?
Thanks!

Try:
e.printStackTrace(System.out);

It is just a recommendation. In eclipse it is fine - I believe it is just the IDE telling you that there are more conventional methods of doing it, like some of the other answers.
I find that it is useful for debugging, and that you should tell users when a fatal error is going to occur, to use a debug mode (like a console switch -d) to collect these logs.

It's probably because printStackTrace() doesn't really handle the error as much as it just dumps the stack in the console. It acts as a placeholder until you replace it with proper error handling (if it is needed at all) and replace the output with a logger of some sort.

e.printStackTrace();
Is not good practice because it prints in the default ErrorStream, which most of the times is the console!
NetBeans should be warning you about that. The good practice about it, is logging the message. Follow same reference:
http://onjava.com/pub/a/onjava/2003/11/19/exceptions.html
EDIT
See first comment bellow to more info.

Just printing a stack trace is not enough. Printing the exception's stack trace in itself doesn't mean that it is completely bad practice, but printing only the stack trace when an exception occurs is an issue.
Always log exceptions(using a good logging framework), but do not expose them to the end-user. And keep ensure that showing stack traces only in development mode.
I myself use(most of the time) logger.log(Level.SEVERE, <exception>.getMessage(), <exception>);.
when netbeans suggest you to handle the exception 'Surround Statement with try-catch', if you click on this, it will generate):
try {
//something need to be handle(exception that throw)
} catch (SQLException ex) {
Logger.getLogger(ClassName.class.getName()).log(Level.SEVERE, null, ex);
}
Which is better than ex.printStackTrace();.
These may help:
Best Practices for Exception Handling
Javarevisited- logging's.
What are the latest options in Java logging frameworks?
Benchmarking Java logging frameworks.

Related

why not debug rather why exception handling

we specify the exception in try and catch.If we know what exception is gonna be generated why go for exception handling rather than just debug that part of the code?
According to Oracle definition of Exception
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.
CONCLUSION:
If you put a try {} catch block you know will always trow an Exception, your code is wrong.
For example, this code compiles? YES, but is wrong
String s = "throwMe!";
try {
int number = Integer.parseInt(s);
} catch (NumberFormatException) {
}
CORRECT EXCEPTION USE
System.out.println("Enter a number");
String s = Scanner..... // user enters something
try {
int number = Integer.parseInt(s);
} catch (NumberFormatException) {
// TELL USER THERE IS A PROBLEM
}
// TELL USER IS A GENIUS
This will have 2 execution flows, the correct one (user is a genius) but in the moment the user enters a value disrupting the flow (Integer.parseInt(s);) the Exception is thrown...
No, exceptions refer to run-time conditions that we cannot foresee
For example, the divide-by-zero error happens due to user inputting wrong data.
So you catch with try-catch
try {
}
catch(ArithmeticException){
}
You don't have to do exception handling or debugging, you can do both and good exception handling helps you debug your code later on.
If nothing else a catch block should print the Stack Trace which gives you information regarding where things went wrong with your code and it's much better than failing silently and then manually debug your whole code to search for the problem.
There are many other advantages to using exceptions for error handling as well.
Try / catch blocks are for errors that you cannot foresee. Things like null pointers and divide by 0 errors don't need a try catch blocks. Those things are typically errors on the part of programmers and should be debugged by the programmers. But things like IOException or SQLException, where you are interfacing with some other system that could fail or give invalid input that the programmer cannot control, those things need a try / catch block.

Java Logging exceptions, use getMessage or toString : log.warn(ex.getMessage()) or log.warn(ex) working with open source

My question is: it better to log with getMessage or with toString or both? taking in to account errors thrown by open source. Saw the questions in the comments but did not get an answer to this. Maybe I missed something ? Do not mind the small performance hit of logging one of them, but do not want to log both unless there is a good reason.
Meaning log(ex) or log(ex.getMessage), Not talking about stack trace.
Saw 1 , 2 and 3
Logging exceptions : which is better:
log.warn(ex.getMessage(), ex) or log.warn(ex, ex);
I noticed sometimes getMessage returns empty or null, so in general practice is there any reason not to use :
log.warn(ex, ex);
As it seems to print the class name and the message (if set) ? I guess one reason could be if a sub class has over ridden to string not to print the message, but in reality do any of the hibernate, apache or spring libs do that?
How about
log.warn("some descriptive message, maybe with context {}",
someId, ex);
The exception details will already be printed as part of the stacktrace, so you don't need to include them in the message usually.
In case you want to suppress the stacktrace and only print the exception message, usually, ex.toString() works better than ex.getMessage(), because it also includes the exception class name, which the message does not. In fact, often the message is empty (for example with NullPointerExceptions).

If RuntimeException is thrown, can it be caught as an Exception?

If I have a try block that throws a RuntimException subclass, can a subsequent catch block catches it as an Exception? Specifically:
public class MyAppException extends RuntimeException {
// ....
}
// In some other part of the code:
try {
// Executing this results with doSomething() throwing a MyAppException.
int x = doSomething();
} catch(Exception exc) {
// Does the thrown MyAppException get caught here?
}
My thinking is yes, because a RuntimeException extends Exception. However I have some production code that is not behaving this way. So obviously, if the answer is no, then that's my answer; otherwise I need to dig down and see why my code is breaking bad. Thanks in advance!
RuntimeException is derived from Exception, so it will get caught.
Having said this, don't do it! Runtime exceptions should be prevented, not caught.
Yes. It will catch RuntimeExceptionbut in case any Exception arise in catch block that you have to catch again.
I would suggest you to make a local deployment and debug the code.
If catch(Exception) is not catching your RuntimeException then your application is not behaving the way you think.
try {
throw new RuntimeException();
} catch (Exception e) {
System.out.println("Caught "+e);
}
prints
Caught java.lang.RuntimeException
Yes. It is possible to catch RuntimeExceptions.
All subclasses of Throwable can be caught.
Yes , you can catch RuntimeException...But i think its not a good approach, if you catch it you should properly manage it. Otherwise the result is out of your hand. Best way is to leave it to JVM . JVM will handle it.
Yes, your thinking is correct, I think the best way to know answer to "just writing the code", let the code tell you the answer. you can see the following simple example code:
package own;
public class MyExceptionTest {
public void testRuntimeException (){
throw new MyException();
}
public static void main(String[] args) {
try{
new MyExceptionTest().testRuntimeException();
}catch(Exception e){
System.out.println(e.getClass().getName());
}
}
}
class MyException extends RuntimeException{
public MyException(){
super();
}
}
I am a project manager in IT and I have had the same argument over and over with my devs and they simply dont care. Browsing the net, even most people advocate catching and throwing RuntimException... Every time I see it I get unbelievably furious about the inaptitude after 10 years of experience....
Rule No.1:
Never ever throw a runtimeexception in Program if you didnt catch a RuntimeException.
Rule No.2:
Only catch a Runtimeexception in order to some really import stuff that has nothing to do with your software: e.g. send a mail to operations emergency shift, log exception, restart the server....
The reason for this is that in good software there is no stacktrace in a logfile. When feel uncomfortable starting to code do this:
Create new class DevelopmentException Extends Exception.
Then goahead and write your code and catch for exception initially. Then you rethrow it as your very own developmentexception. In the method catching it you log it.
Now: Everyday grep for your very personal DevelopmentException. If you find one this means there is still work to do. Go into your code and see where the Exception came from and catch it beforehand.
Ideally you will never see a DevelopmentException in this part of your program again. Repeat until there are 0 Stacktraces in your Software left and you have perfected Exception handling.
The biggest issue with throwing and catching runtime exception is that the compile ignores it. So this means when one of your colleagues writes a booking interface and throws RuntimeException when there is a value missing (yeah, ppl really do)... ...the compiler will not show you that there might be a runtimeexception. Now, when you dont catch it then your program might just shut down without any logging.
Why is it called RuntimeException?
Many mistake this for Error during Runtime of Program, however it actually means 'An Exception so utterly destructive that the Java Runtime Environment need to be stoppep'. In other words it meand: OutOfMemory, BrokenRam, FaultyImplementation of JRE, etc... basically stuff that tell you: Program cannot run because PC is crashing....
Just my 2 cents.
Anyone experienced the same stuff?
PS: Regarding continous removal of stacktraces:
Once you see an exception try to catch it with e.g. NullpointerException.
When you see Nullpointerexception go to your code and remove the stacktrace, and just log.WARN(NullpointerOccured) and write your Program to retry or so...
Ideally you repeat until you never see a Stacktrace again.
When you cannot see a stacktrace ever it means all that could possibly go wrong is taken care of (Except for RuntimeException of course)

JVM - Print Stack trace without explicit call

Is there a way in java to print a stack trace of any exception in a catch block without making code modifications. I was told that there was a JVM arg you could use to produce stack traces of all exceptions for debugging, although I can't find any documentation on this. The only solution I can think of for this is to use aspectj and create an aspect on any exception that is created and print the stack trace. I was hoping there was a better solution than aspects.
Thanks,
Steve.
--Edit--
So what I want to find out is lets say I have this code:
try {
throw new Exception();
}
catch (Exception e) {
//Ignore exceptions
}
I would like to see the e.printStackTrace() even though no call is made to it. This can help with debugging a jvm crash I am seeing, and there is a lot of error hiding going on.
As Marko Topolnik said, logging any exception may take a bit of work, but you can also implement a custom uncaught exception handler to do whatever you please with uncaught exceptions.
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
private final Logger log = Logger.getLogger("EXCEPTION");
public void uncaughtException(final Thread t, final Throwable e) {
log.logp(Level.SEVERE, "EXCEPTION", "", "Unhandled exception in thread " + t.getName() + ": ", e);
}
});
Better solutions would only exist for unhandled exceptions. There is no first-class support to log any exception, anywhere that happens inside normally functioning code. I would recommend you try with aspects and intercept the Throwable constructor calls, if that's at all possible. If possible, you may still get false positives because instantiating exception does not entail throwing it.

Java - ignore exception and continue

For my Java application, I am creating an instance of a user information object and populating it with a service that I don't control the source for.
The code looks like this:
// username given as parameter
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (Exception e) {
// Whatever
}
If LDAPService.findUser() can't locate a user, it will throw a NullPointerException and grind the rest of my application to a stop. It's okay if the user information isn't populated, so I want to be able to continue without causing everything else to start throwing exceptions.
Is there a way to do this?
I've upvoted Amir Afghani's answer, which seems to be the only one as of yet that actually answers the question.
But I would have written it like this instead:
UserInfo ui = new UserInfo();
DirectoryUser du = null;
try {
du = LDAPService.findUser(username);
} catch (NullPointerException npe) {
// It's fine if findUser throws a NPE
}
if (du != null) {
ui.setUserInfo(du.getUserInfo());
}
Of course, it depends on whether or not you want to catch NPEs from the ui.setUserInfo() and du.getUserInfo() calls.
You could catch the NullPointerException explicitly and ignore it - though its generally not recommended. You should not, however, ignore all exceptions as you're currently doing.
UserInfo ui = new UserInfo();
try {
DirectoryUser du = LDAPService.findUser(username);
if (du!=null) {
ui.setUserInfo(du.getUserInfo());
}
} catch (NullPointerException npe) {
// Lulz # your NPE
Logger.log("No user info for " +username+ ", will find some way to cope");
}
You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.
try{
throw new Exception();
}catch (Exception ex){
ex.printStackTrace();
}
System.out.println("Made it!");
However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.
It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.
However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.
You are actually ignoring exception in your code. But I suggest you to reconsider.
Here is a quote from Coding Crimes: Ignoring Exceptions
For a start, the exception should be logged at the very least, not
just written out to the console. Also, in most cases, the exception
should be thrown back to the caller for them to deal with. If it
doesn't need to be thrown back to the caller, then the exception
should be handled. And some comments would be nice too.
The usual excuse for this type of code is "I didn't have time", but
there is a ripple effect when code is left in this state. Chances are
that most of this type of code will never get out in the final
production. Code reviews or static analysis tools should catch this
error pattern. But that's no excuse, all this does is add time to the
maintainance and debugging of the software.
Even if you are ignoring it I suggest you to use specific exception names instead of superclass name. ie., Use NullPointerException instead of Exception in your catch clause.
You can write a try - catch block around the line you want to have ignored.
Like in the example code of yours. If you just continue your code below the closing bracket of the catch block everythings fine.
LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..
Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

Categories

Resources