Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

finally clause

 
Neha Mohit
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could use a return statement in the catch block, which should stop execution of the finally block.
 
Henry Wong
author
Marshal
Pie
Posts: 20894
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeff Albertson
Ranch Hand
Posts: 1780
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If this isn't one of those tricky certification questions, you could always define a boolean flag:
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic