I have wrote the code below which was taken from Java How to program 9th Edition – Paul and Michelle Harvey – The code works fine but the problem is that every time I execute it, it gives me uncertain results in which the exceptions are handled – e.g. please look at the output of the code snippet. can you please help me understand why this behavior is occurring ?
public class Test {
public static void main(String[] args) {
try {
// call method throwException
throwException();
}// end try
catch (Exception e) {
System.out.println("Exception handled in main");
}// end catch
// call method doesNotThrowException
doesNotThrowException();
}
private static void throwException() throws Exception {
try {
System.out.println("Method throwException.");
throw new Exception(); // generate exception
}
catch (Exception exception) {
System.err.println("Exception handled in method throwException");
throw exception;
}
// executes regardless of what occurs in try ... catch block
finally {
System.err.println("Finally executed in throwException.");
}
}// end of method throwException
private static void doesNotThrowException() {
try {
System.out.println("Method doesNotThrowException.");
}
// catch does not execute as the method does not throw any exceptions
catch (Exception exception) {
System.err.println(exception);
}// end catch
// executes regardless of what occurs in try ... catch block
finally {
System.err.println("Finally executed in doesNotThrowException");
}
}// end of deosNotThrowException
}//end Test Class
OUTPUTS:
1)
Method throwException.
Exception handled in method throwException
Finally executed in throwException.
Finally executed in doesNotThrowException
Exception handled in main
Method doesNotThrowException.
2)
Exception handled in method throwException
Finally executed in throwException.Method throwException.
Finally executed in doesNotThrowException
Exception handled in main
Method doesNotThrowException.
Different outputs on different runs are because of you’re using 2 different output streams: out and err. It’s up to the OS to flush such I/O streams and it does so in different ways on each run depending on other factors that have nothing to do with your program. The only thing the OS guarantees is that the order for out and the order for err are preserved, but not the order between them.