Angry-d
Angry-d

Reputation: 87

Javae exception handling output error

I'm trying to run an example from "How to program in Java 9th edition". This example about exception handling, and how to use it. Every time I run my program, I got different output. Why?! I'm using NetBeans IDE. The code is:

public class StackUnwinding {
    public static void main(String[] args){
        try{
            method1();
        }catch(Exception exception){
            System.err.printf("%s\n\n", exception.getMessage());
            exception.printStackTrace();

            StackTraceElement[] traceElement = exception.getStackTrace();

            System.out.println("\nStack trace from getStackTrace:");
            System.out.println("Class\t\tFile\t\tLine\t\tMethod");

            for(StackTraceElement element : traceElement){
                System.out.printf("%s\t", element.getClass());
                System.out.printf("%s\t", element.getFileName());
                System.out.printf("%s\t", element.getLineNumber());
                System.out.printf("%s\t", element.getMethodName());
            }
        }
    }

    public static void method1() throws Exception{
        method2();
    }

    public static void method2() throws Exception{
        method3();
    }

    public static void method3() throws Exception{
        throw new Exception("Exceptions thrown in method3");
    }
} 

Upvotes: 1

Views: 71

Answers (1)

M A
M A

Reputation: 72884

The output may sometimes interleave between the System.err error stream and the System.out output stream due to the buffering of the streams and the time at which the streams flush. If you only print using the error stream in your code, the output will always be the same.

If you only use the System.out you may still get different results because the printStackTrace() uses the error stream internally.

Upvotes: 2

Related Questions