Saturday, January 16, 2016

Extracting root cause from Stack Trace

Don't tell me the problem; show me the logs first!

Whether you are a fresh graduate, an experienced programmer, QA engineer, production engineer or even a product manager - a good understanding of stack trace is vital to crack critical issues. Your ability to find the real culprit from a lengthy stack trace will be instrumental in resolving a problem. This is even more important if you work on a distributed system where you use many libraries so stack trace is not well structured. Let's start with a simple scenario-

Scenario 1: Simple

This is the most trivial case, where the exception gets thrown by a method of your project and during the call duration, it doesn't go out of your code base. This is the most trivial scenario which you will encounter but very important to understand how the stack trace gets printed.

Shown below is Eclipse screenshot of MyController.java which two classes. Right click and run the program. 

Let's Decode Above stack trace:
  • RuntimeException is shown in line number 29, in method MyService.four()
  • Method MyService.four() gets called by MyService.three() in line number 25
  • Method MyService.three() gets called by MyController.two() in line 11
  • Method MyController.two() gets called by MyController.one() in line 6
  • Method MyController.one() gets called by MyController.main() in line 17


First frame of stack trace holds all important information required to know the root cause. 
Be mindful of the very important line number 

Scenario 2: Chain Of Exception

Let's modify above code a bit by catching exception at the origin and then throwing a brand new Exception. 


Let's Decode Above stack trace:

This stack trace has a caused by section. It has only one caused by but in real applications you can have multiple caused by sections. The last caused by will have the root cause of the exception.


Caused by: java.lang.RuntimeException: here, comes the exception!
at MyService.four(MyController.java:30)


... 4 more


But, if you are using external jars or libraries, finding the root cause could be bit tricky as the real reason might be nested deep inside. In such case you should look for Class.method name which belongs to your application. Also, you should look the complete stack trace carefully as the real root cause could lie in any part of stack trace. 


References:
http://www.nurkiewicz.com/2011/09/logging-exceptions-root-cause-first.html
http://stackoverflow.com/questions/12688068/how-to-read-and-understand-the-java-stack-trace
http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors


No comments:

Post a Comment