Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please Help with the flow of this code

 
Pratap Pandey
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Sheriff
Pie
Posts: 49782
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Campbell

Thanks for correcting!! Yes finally is executed in any case.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic