'Why exception is printed in the end on the console while running below java code [duplicate]

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?



Solution 1:[1]

Although System.out and System.err are both printed to the console, they are two different streams, and I don't think there is any requirement about which order they get flushed. printStackTrace() goes to System.err.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew Lazarus