File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes finally clause Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "finally clause" Watch "finally clause" New topic

finally clause

Neha Mohit
Ranch Hand

Joined: Apr 25, 2006
Posts: 87
Hi ,
How can we stop a finally block from getting executed, I know one way that is by creating an exception in the try block and calling System.exit() in catch block is there ant other way .

Thanks in advance.
M. Bunyard

Joined: Mar 28, 2006
Posts: 3
You could use a return statement in the catch block, which should stop execution of the finally block.
Henry Wong

Joined: Sep 28, 2004
Posts: 20536

Originally posted by M. Bunyard:
You could use a return statement in the catch block, which should stop execution of the finally block.

No... the finally block will execute just after the calculation of the return value, and prior to the actual return from the catch block.

I am assuming this question is academic. After all, if you can modify the try and catch block to avoid the finally block, why can't you just modify the finally block?


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
If this isn't one of those tricky certification questions, you could always define a boolean flag:

There is no emoticon for what I am feeling!
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

it is a really bad practise to ... throw an exception from with in a catch block.

Oh I don't know. How about when you are catching a "low level" execption (i.e. meaningless to the user) and rethrowing it as an application exception?

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

Originally posted by faisal usmani:

it is a really bad practise to return from a catch block

And I'll object to this other half. Returning from a catch block is a fine thing to do -- you handle a problem, and then abort the routine.

It's returning from a finally block that is bad to do, because it will cancel any pending returns or exceptions from the associated try and catch block.

[Jess in Action][AskingGoodQuestions]
I agree. Here's the link:
subject: finally clause
It's not a secret anymore!