Please help me to interpret the o/p of this program.
public class exceptchk { public static String op = ""; public static void foo(int i) { try { if(i==1) { throw new Exception(); } op +="1"; System.out.println(op + "In TRY"); } catch(Exception e) { op +="2"; System.out.println(op + "In Catch"); return; } finally { op +="3"; System.out.println(op + "In FINALLY"); } op +="4"; System.out.println(op + "In Method"); }
public static void main(String[] args) { // TODO Auto-generated method stub foo(0); foo(1);
}
}
The o/p is : 1In TRY 13In FINALLY 134In Method 1342In Catch 13423In FINALLY
John Dell'Oso
Ranch Hand
Joined: Apr 08, 2004
Posts: 130
posted
0
Pratap,
Is there anything in particular that you don't understand? Were you expecting the output to be different?
Regards, JD
Satya Maheshwari
Ranch Hand
Joined: Jan 01, 2007
Posts: 368
posted
0
The general flow in try-catch block in java is as follows: start of method->try->catch(exception raised)->finally ->return from method
start of method->try->method code after try-catch-finally(no exception thrown in try)->return from method
Thanks and Regards
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32654
4
posted
0
I find your flow difficult to understand. I presume you mean
try->exception->catch->finally->everything else
OR
try->no exception->finally->everything else.
The finally block is executed whether there is an exception thrown or not.
Satya Maheshwari
Ranch Hand
Joined: Jan 01, 2007
Posts: 368
posted
0
Hi Campbell
Thanks for correcting!! Yes finally is executed in any case.