PrintStackTrace() in Exception Handling - java

What does this method do? I found an Android code on internet about exception handling in which the guy used this function in catch{} He didn't explain properly why this function/method is used.

Check this JavaDoc. Stacktrace is used in debug mode. Each method is displayed from most generat to the specific method where the exception was thrown.
Think about it as a stack which has each method call involved in the cause of that exception.
In addition, using printStackTrace() method is considered bad practice because System.err file is used and the method is not thread safe. Better use a logger.

it prints the stack where the exception occured. If there is debug information then it will show the line of code where each call was at to help you find the source of the problem.

This method prints the entire stack trace of the methods that got called before the exception has been raised. It is very helpful while debugging since you will know the path of execution.

It prints the stack trace of the Exception to System.err.
It's a very simple, but very useful tool for diagnosing an Exception. It tells you what happened and where in the code this happened.
source: What is the use of printStackTrace() method in Java?

Related

Understanding suppressed exceptions

I've just run into a logback bug related to loops in the exception chains. In my case, I have
throwable.getSuppressed()[0].getCause() == throwable
The logback bug doesn't bother me at the moment, my problem is the cycle.
I'm staring on my the stacktrace and I can't understand how it happens.
The stacktrace is very long an involves my own code only. It spans many classes, so I can't post it here without posting too much code.
I check that
I never use Throwable::addSuppressed explicitly (that's sure)
no involved exception gets thrown in a finally block
any caught exception is used as the cause
but I might be overlooking something. Could someone tell if its possible to get the above cycle when my assumption is valid?
There's a place where the exception gets stored to be wrapped and rethrown later, could this be the culprit?
Could someone give a simple example producing such a cycle?

In IntelliJ, when I trigger an exception, how do I look back and find which line threw it?

When I debug a block of Java code by stepping through it, some line throws an exception and I need to search for which line threw it.
But now I am already in the middle of the exception handler code. Is there a way to trace which line of code in my procedure that threw this exception?
I am using IntelliJ Idea 16.2.
If you have the exception in scope while in the debugger session, press Alt+F8 in Mac (Evaluate Expression), not sure other OS, then execute exception.printStacktrace() and you'll get clickable stack trace in the Console window (or just look at the stackTrace array in the class inspector).
There's a few ways. First of all, if you don't catch the exception at all, the JVM will barf it into the standard error stream (stderr) and your thread will terminate. If this happens, IntelliJ will print it in the output console (If you're using the Darkula theme, I believe that stderr comes out in red text) with a full stack-trace. IntelliJ also formats the output so that you can click on the line-numbers of each stack element and see exactly where the exception came from.
Alternatively, if you have caught the exception and want to handle it more gracefully but still want to output the line numbers, you can tell the Exception to print itself to a particular PrintStream (such as System.out or System.err) with the java.lang.Throwable#printStackTrace(java.io.PrintStream) method.
Now, if you're actually debugging the application (Stepping through it with breakpoints and whatnot), things are even easier and more detailed. IntelliJ's Debugger is excellent for viewing the whole stack (albeit a bit slow if you're debugging a remote application). It looks something like this: http://i.imgur.com/Yv4IgKj.png
Up top, you have your source code. Down below you have your Debugger. The "Frames" pane is your call-stack; you can click on any method in the stack to view it AND all of its stack variables. With a few clicks, you should be able to see where your exception is being thrown from, just by navigating the stack frames and looking for the relevant throw statement.
BUT WAIT, THERE'S MORE! Do you know what exception you're looking for and want to break as soon as it's thrown? IntelliJ can do that! Click on the "View Breakpoints" button (off to the left side of the Frames pane) and you can add an Exception Breakpoint simply by specifying the name of the Exception class that you want to catch. As soon as the exception of that time is thrown, your debugger will pause and take you to it. This makes navigating to a particular Exception trivial.
Put a breakpoint in your method that invokes this procedure, use F7 to move between lines in order of execution, F8 to go to the next breakpoint an F9 to end the method process. You can use a try catch block yo handle this exception and log in the console what type is and what line throw it.
Hope it helps.

Chained Exception versus PrintStackTrace

Chained Exception is useful in cases in which knowledge of an underlying cause is useful. The Throwable getCause( )method returns the exception that underlies the current exception.
On the other hand, if we call PrintStackTrace() in the catch block, we will have the entire logs printed in the logger file(and in eclipse console). The detailed log will show the exception occurred, and the underlying chain of exceptions as well.
So, what is the primary difference in the usages of both of them.
One approach is to provide debug information (PrintStackTrace). The other approach is for actual flow control (Throwable.getCause()).
(Usually) the underlying cause is considered an implementation detail, and therefore should not be used for flow control. Add the information you need to the main exception or create multiple types for exception.

How do stack traces get generated?

No single method in a program "knows" where it is on the stack. All it knows is its own little job, and it does that and returns. So when an Exception is thrown and a stack trace is printed, where does this come from?
Is there implicitly a separate Thread running alongside of every application in the JVM that's monitoring the state of the program? Or does the JVM itself hold this information and the Exceptions somehow pull that data from it when they are thrown?
If either of these is the case, is it possible to use some call to retrieve a stack trace (either from the monitor Thread or the JVM) without throwing an Exception?
Every thread will have its own stack. Each method call creates a stack frame. If something wrong happened in code of any method, that will propagated to caller method. This way JVM can trace which method generated error and what is the call hierarchy.
If you observe the stack trace properly, you will see the method where error occured at top and the hierarchy in bottom.
There is a great lecture in youtube by a Stanford professor to understand how does it work. I would suggest watching it.
NOTE: This is theory. If you would like to know how API works, #Peter Lawrey answer may help you.
It comes from the Thread class that is running through the code.
Thread.dumpStack();
To see it you can just:
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
for (int i=0; i < trace.length; i++)
System.out.println("\tat " + trace[i]);
You can know the Thread a method belongs to by using Thread.currentThread. Using this thread, you can get the StackTrace, because there is a stack for every thread in the JVM. Also, the main program runs in the main thread.
When you create a Throwable (not when you throw it) it records the stack trace is a low level/hidden way associated with the Throwable. When you call getStackTrace() the first time it creates the StackTraceElement[] objects from the low level information. It doesn't this lazily as the stack trace is often not used.

Java - make custom runtime error not dump trace

I have a kludgey use of Java RuntimeError in which I fully handle the error. Only problem is it gives me annoying trace telling me where the runtime error that I derived and threw occurred. How to suppress this trace?
For reference, the issue is I subclassed a non-throwing class and needed my subclass to throw. It was either "rewrite my program to read like a C program" or "use runtime error to bypass throw specification requirement." Obviously I'm finding the throw spec requirement very counterproductive right now - other workarounds that don't involve maintaining a bunch of "workIsDone" variables would be appreciated.
Without code it's awfully hard to know what you're talking about, but in general, stack traces come from a handler catching an exceptions and calling printStackTrace() on it. The stack trace doesn't appear unless something asks for it. Now, if an exception makes it all the way to the top of (for example) the AWT event thread stack, then the default handler will print it out this way.
As a rule, you want to handle exceptions. It can be a fine strategy to use runtime exceptions to get around the fact that some superclass method doesn't declare any exceptions, but then you take responsibility for always catching those exceptions. If you can't -- i.e., if some other code is going to catch them instead -- then this is a bad strategy and you can't use it.

Categories