class TestExceptions {
public static void main(String[] args) throws Exception {
try {
System.out.println("try");
throw new Exception();
} catch(Exception e) {
System.out.println("catch");
throw new RuntimeException();
} finally {
System.out.println("finally");
}
}
}
Following are the outputs when I try to run the code in eclipse multiple times. I believed so far that whenever the last line of the code from either try/catch block is about to be executed (which could be return or throws new Exception() type of stmt), finally block will be executed, but here the output different every time? Can anyone clarify if my assumption is right or wrong?
try
catch
Exception in thread "main" finally
java.lang.RuntimeException
at TestExceptions.main(TestExceptions.java:9)
Exception in thread "main" try
catch
java.lang.RuntimeException
at TestExceptions.main(TestExceptions.java:9)
finally
The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.
Java try, catch and finally blocks helps in writing the application code which may throw exceptions in runtime and gives us a chance to either recover from exception by executing alternate application logic or handle the exception gracefully to report back to the user.
The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.
If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method. The finally block is always executed, whether an exception is thrown or not.
This is clearly because eclipse is printing the error stream
and output stream
without proper synchronization in console. Lot of people have seen issues because of this.
Execute the program in a command prompt and you will see proper output every time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With