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 Exception in 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 "Exception in finally clause" Watch "Exception in finally clause" New topic
Author

Exception in finally clause

Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
Another question from the Sun Certified Java Essentials link. It states:

finally blocks execute no matter what, in other words, whether the code executes without an exception, or an exception is thrown and successfully caught, or an exception is thrown and not caught. This is useful because, except for code in a finally block, if an exception is thrown and not caught, the execution of the rest method is abandoned


I created the program below to test the error process in the finally clause as listed below:


When it runs, I get the Arithmetic error and the "After second error" line doesn't print. Does this mean that if an error is thrown in the finally block and not caught, it would also abandon executing the rest of the code as it does for other try blocks or is it just because I am throwing a deliberate Runtime exception instead of a checked exception? I guess what I am saying is that it appears as if the finally block is subject to the same code abandonment rules as the rest of the try blocks. Does this mean you should be careful with your code in a finally block to make sure you either don't throw any exceptions or catch them in try/catch/finally constructs?
pinky yadav
Ranch Hand

Joined: Jun 17, 2002
Posts: 44
you are right finally is a block of code which like any block of code can throw exception and rest of the statements in the block are not executed
Jeffrey Hunter
Ranch Hand

Joined: Apr 16, 2004
Posts: 305
Regardless of where the exception occurs, the JVM will handle it in a consistent manner, so yes, the code in a finally block is subject to the same exception handling logic as any other program block. Naturally, it would not be good programming practice to deeply nest try/catch/finally blocks, so you'll want to limit the amount of logic you place in your finally block -- perform only the essential "clean-up" needed so your program may "gracefully" (hahah, don't we wish), recover.
Chengwei Lee
Ranch Hand

Joined: Apr 02, 2004
Posts: 884
Yes, for me, the most often encountered exception in the finally block is the infamous NullPointerException

Keep a look out for codes that could gives you that


SCJP 1.4 * SCWCD 1.4 * SCBCD 1.3 * SCJA 1.0 * TOGAF 8
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exception in finally clause