In my way to learn exception handling in java I've encountered unusual behavior of exceptions to be printed on console.
Java Code:
public class ExceptionHandlingRunner2 {
public static void main(String[] args) {
method1();
System.out.println("Main Ended");
}
private static void method1(){
method2();
System.out.println("Method1() Ended");
}
private static void method2() {
try{
String str = null;
str.length();
System.out.println("Method2 ended");
} catch (NullPointerException ex){
System.out.println("in catch NullPointerException");
ex.printStackTrace();
}catch (Exception ex){
System.out.println("in catch Exception");
ex.printStackTrace();
}
}
}
Output after trying to Debug
in catch NullPointerException
java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null
at src.in28minutes.exceptionhandling.ExceptionHandlingRunner2.method2(ExceptionHandlingRunner2.java:20)
at src.in28minutes.exceptionhandling.ExceptionHandlingRunner2.method1(ExceptionHandlingRunner2.java:13)
at src.in28minutes.exceptionhandling.ExceptionHandlingRunner2.main(ExceptionHandlingRunner2.java:8)
Method1() Ended
Main Ended
Output after running(Exception is printed at the end)
Method1() Ended
Main Ended
java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null
at src.in28minutes.exceptionhandling.ExceptionHandlingRunner2.method2(ExceptionHandlingRunner2.java:20)
at src.in28minutes.exceptionhandling.ExceptionHandlingRunner2.method1(ExceptionHandlingRunner2.java:13)
at src.in28minutes.exceptionhandling.ExceptionHandlingRunner2.main(ExceptionHandlingRunner2.java:8)
Why order of printing the Exception at console varies while Running?