aspose file tools*
The moose likes Beginning Java and the fly likes NullPointerException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "NullPointerException" Watch "NullPointerException" New topic
Author

NullPointerException

Jon Camilleri
Ranch Hand

Joined: Apr 25, 2008
Posts: 660

Why does the following code retain the null value of in? Basically I wanted to wrap the code around try...catch block to ensure that "database.properties" exists where the IDE is looking for it..



Jon
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38896
    
  23
If an Exception is thrown in the try, the value of in will remain null.
Jon Camilleri
Ranch Hand

Joined: Apr 25, 2008
Posts: 660

Campbell Ritchie wrote:If an Exception is thrown in the try, the value of in will remain null.


Thanks, hence the appropriate exception handler must be written.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38896
    
  23
You've already got the Exception handler. You can now proceed with if (in != null) ... tests.
Jon Camilleri
Ranch Hand

Joined: Apr 25, 2008
Posts: 660

Campbell Ritchie wrote:You've already got the Exception handler. You can now proceed with if (in != null) ... tests.


That's a good point, I was just thinking that since my block of statements handles FileNotFoundException, I would add another catch statement that catches all other exceptions:
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38896
    
  23
It might be better to catch an IOException there, rather than declaring it.

There is another way of opening streams which Rob Spoor showed me a few weeks ago, which avoids the need for null checks, but I can't remember where it is. It's somewhere on the Ranch.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14156
    
  19

You could do that but that would not solve the problem, since the code that is in the try-block will not throw any other checked exceptions than IOException, and when it throws an unchecked exception you probably wouldn't want to catch it anyway. The code after the catch blocks would still be reached with in being null.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38896
    
  23
The != null check you showed is in the wrong place; it will actually make things worse there. You initialise the Stream inside a try; you use the != null check afterwards. If you have all the reading done inside the same try, you only need the != null check when you close the stream.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: NullPointerException