finally block consumes/stifles exception

S

Steve Claflin

I was rather surprised at the outcome of this code, which I created to show
someone how a finally block will run even if the try or catch block returns
from the method:
 
L

Loveen

Hi
Take this example...

public class DebugFinally {
public static void main(String[] args) {
try{
int number = Integer.parseInt("1245");
}catch(Exception ex){
System.out.println("In Catch");
return;
}finally{
System.out.println("In Finally");
}
System.out.println("Not Returned");
}
}

Output:
In Catch
In Finally

As you see above the program performed what was written in Catch but
after that it directly goes to finally block and execute what ever is
written in it, after that it comes back to the catch block to call the
return.

Basically internally the compiler executes whatever is written in the
finally block before executing any statement which takes the control
out of try/catch construct.

But, there is one exception to this. If I call System.exit(0); in place
of return then, program would end abruptly without giving care to
whatever is written in finally block.

And in that scenario the output would be modified as follows:

}catch(Exception ex){
System.out.println("In Catch");
System.exit(0);
}finally{
System.out.println("In Finally");
}

Output:
In Catch
 
R

Rhino

Steve Claflin said:
I was rather surprised at the outcome of this code, which I created to show
someone how a finally block will run even if the try or catch block returns
from the method:
Maybe you'd like to try again? This time _with_ a code fragment?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,765
Messages
2,569,568
Members
45,042
Latest member
icassiem

Latest Threads

Top