File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question on finally Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question on finally" Watch "Question on finally" New topic
Author

Question on finally

V Bose
Ranch Hand

Joined: Jul 10, 2003
Posts: 113

The finally statement is always executed right ? If Line 6 throws an IOException, after catching it, does the JVM try line 13. If so would it not throw a null pointer exception if we assume the out variable in LIne 6 was never initialized?
Chris Allen
Ranch Hand

Joined: Feb 01, 2003
Posts: 127
I tried this code and did indeed get a NullPointerException. I am guessing that this is not caught by the compiler because it is a Runtime exception?
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
it SHOULD throw an NPE if line 6 fails.
The IOException is thrown on line 6, leading to the catch executing.
After that, the finally block is executed yielding the NPE because out is null (which is the result when the constructor fails).
So you would get first a notice "IO Error." followed on the next line by "NullPointerException at line 13".
Compiler doesn't check for NPE and other RuntimeExceptions (which is of course why it's called RunTimeException).
A better way to write line 13 would therefore be


42
Madhu GM
Greenhorn

Joined: Mar 09, 2004
Posts: 11
Hi,
Before closing the resources in finally block you have to make sure that the resource is checked for null..
Ex:
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question on finally