• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If conditional not branching correctly

 
Nikhil Pujari
Greenhorn
Posts: 21
C++ Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The program below was taken from the official SunJava tutorial. It demonstrates how the ByteStream classes like FileInputStream and FileOutputStream work. The program reads characters from one file and puts them into another file. I made the input file - xanadu.txt - unavailable (i.e., did not create the file). This results in an exception at line 10 and control immediately jumps to the finally block.

My problem is with the two if statements in the finally block. The second if statement - if(out!=null) - evaluates to true and "out.close()" is executed even though "out" is equal to null. The problem, however, corrects itself when I put the if(out!=null) statement above the if(in!=null) statement. Why is the result changing based on the placement of the if statement?

Here's the code:


 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
welcome to the ranch

irrespective of where ever you place the if condition, the null check will return false for the variable out and the close() will not get executed.

Did you try using System.out.println() inside the if condition that checks out != null? If so are you sure the File not found exception occurs every time?
 
Harsha Smith
Ranch Hand
Posts: 287
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That won't happen Nikhil!
 
Nikhil Pujari
Greenhorn
Posts: 21
C++ Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@John Jai: Thanks, I'm happy to be here

Its strange. I tried using System.out.print inside " if(out!=null) ". It (System.out.print) was not executed, but the out.close() line was. This happened even though both those statements were within a block:

if(out!=null)
{
System.out.print("hello");//was skipped over
out.close();//was executed
}

btw, I am using NetBeans.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do you know that out.close() was executed? If the creation of the InputStream indeed caused an exception, out would have remained null and the entire block would be skipped.
 
Nikhil Pujari
Greenhorn
Posts: 21
C++ Firefox Browser Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I used the line-by-line debugger in Netbeans.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic