A few days ago I asked a question about reading from file until the input has finished. I’ve received some responses which I studied, but I have one question somehow relevant to the topic: why do I have to use some additional tests, “finally” clause and another try-catch there instead of just:
DataInputStream reading = null;
try{
reading = new DataInputStream(new FileInputStream("tes.t"));
while(true)
{
System.out.println(reading.readInt());
System.out.println(reading.readDouble());
}
}catch(IOException xxx){System.err.println("Error: " + reading.getMessage());}
catch(EOFException xxx){reading.close();}
Why is this not enough? I mean – as soon as we reach EOF, we’ll have an exception. Otherwise, we catch the exception and print the error message. Why do we need additional tests? What’s wrong with this approach?
EDIT: OK, I now understand why it’s a bad thing. But what about if I made the code like this:
DataInputStream reading = null;
try{
reading = new DataInputStream(new FileInputStream("tes.t"));
while(reading.available()!=0)
{
System.out.println(reading.readInt());
System.out.println(reading.readDouble());
}
}catch(EOFException xxx){}
catch(IOException xxx){System.err.println("Error: " + reading.getMessage());}
Is checking the value of reading.available() a better test for the input end or just as bad?
It’s not elegant to control your execution flow with exceptions. EOF is a normal situation while reading a file so it should be handled in other way.
The more elegant code would be:
source: Unknown buffer size to be read from a DataInputStream in java
Here is you can find very good explaintation why you shouldn’t control flow with exceptions: Why not use exceptions as regular flow of control?