Monday 25 March 2013

Exception StackTrace

When a java exception is thrown we get a nice stack trace to help for debugging purposes and to know more information about the exception and its source.
public class ExceptionStack {
    public static void main(String args[]) {
      int[] tempArr = new int[5];
    System.out.println(tempArr[10]);
    }
}
If the above source code listing is executed we get the following exception.
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 10
at ExceptionStack.main(ExceptionStack.java:4)
This is the exception stack trace which gives information on what type of exception is thrown and which line number, method is the cause of it. For this example, the stack trace tells that the type of exception occurred isArrayIndexOutOfBoundsException, it occurred because it 10 is not a valid array location, then the exception occurred at source code line number 4, in method main. This is sufficient to understand and fix this issue.
Exception stack trace also give complete list of method calls in the sequence flow till it reached the exception line. Look at the following source code listing where the line where exception can happen is moved into a method.
public class ExceptionStack {
    public static void main(String args[]) {
    int value = get(10);
    System.out.println(value);
    }
 
    public static int get(int location) {
    int[] tempArr = new int[5];
    int result = 0;
    result = tempArr[location];
    return result;
    }
}
For this example source code, we get the following exception stack trace.
Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 10
at ExceptionStack.methodA(ExceptionStack.java:8)
at ExceptionStack.main(ExceptionStack.java:3)
This stack trace adds one more line of information. Starting from bottom-up, it gives the first method where the execution flow started and the call is made, then the next method in sequence flow. Similarly if we have multiple methods, we will get all the methods in the sequence flow listing in the stack trace.

No comments:

Post a Comment