Originally posted by Kanchan Narang:
Hi All ,
I m bit confused about the way try ,catch,finally bolcks work.
--- code snippet ----
try {
throw new IOException();
}catch(Exception e){
e.printStackTrace();
}fianlly{
System.out.println("ABC");
}
O/p:
ABC
Exception Trace .
It is fairly simple:
The try block contains the code which is ran for business purposes. In this block an error might be thrown (either explicitly (as per your example) or implicitly (another method may throw an error), this error is processed (caught) in the catch block. Here the error is processed, however the finally block will always be run, whether there is an error or not. What you have shown in your output is that the finally block is run before the catch block. I'm not too sure if an processing order is explicitly given in the JVM descriptions, and to be honest I could have sworn that the catch block would be processed before the finally block. This proves the validity of the point that in the finally block there should never be any code which is core to the program-functionality but only general closure methods (as the finally block will also be run if no error has been thrown), and the catch block should no rely on the availability of any resources which are processed in the finally block (as your trial has shown that the finally block may -and perhaps always will- be run before the catch block).