File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "finally clause" Watch "finally clause" New topic
Author

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
Greenhorn

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
author
Sheriff

Joined: Sep 28, 2004
Posts: 18845
    
  40

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?

Henry


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
Bartender

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
Marshal

Joined: Jul 08, 2003
Posts: 24184
    
  34

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]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: finally clause