Wednesday 16 March 2016

The Java Language: Stack Traces

Because an exception can bubble up quite a distance before it is caught and handled, we may need a way to determine exactly where it was thrown. It’s also very important to know the context of how the point of the exception was reached; that is, which methods called which methods to get to that point. For these kinds of debugging and logging purposes, all exceptions can dump a stack trace that lists their method of origin and all the nested method calls it took to arrive there. Most commonly, the user sees a stack trace when it is printed using the printStackTrace() method.

 try {  
 // complex, deeply nested task  
 } catch ( Exception e ) {  
 // dump information about exactly where the exception occurred  
 e.printStackTrace( System.err );  
 ...  
 }  
For example, the stack trace for an exception might look like this:
 java.io.FileNotFoundException: myfile.xml  
 at java.io.FileInputStream.<init>(FileInputStream.java)  
 at java.io.FileInputStream.<init>(FileInputStream.java)  
 at MyApplication.loadFile(MyApplication.java:137)  
 at MyApplication.main(MyApplication.java:5)  
This stack trace indicates that the main() method of the class MyApplication called the method loadFile(). The loadFile() method then tried to construct a FileInput Stream, which threw the FileNotFoundException. Note that once the stack trace reaches Java system classes (like FileInputStream), the line numbers may be lost. This can also happen when the code is optimized by some virtual machines. Usually, there is a way to disable the optimization temporarily to find the exact line numbers. However, in tricky situations, changing the timing of the application can affect the problem you’re trying to debug, and other debugging techniques may be required. Methods on the exception allow you to retrieve the stack trace information programmatically as well by using the Throwable getStackTrace() method. (Throwable is the base class of Exception and Error.) This method returns an array of StackTraceEle ment objects, each of which represents a method call on the stack. You can ask a Stack TraceElement for details about that method’s location using the methods getFile Name(), getClassName(), getMethodName(), and getLineNumber(). Element zero of the array is the top of the stack, the final line of code that caused the exception; subsequent elements step back one method call each until the original main() method is reached.

0 comments:

Post a Comment