Understanding Exceptions
Hi All
I'm trying to understand Exceptions and IO in Java and am faced with
the following small program which just copies one file to another.
The problem is that Eclipse tells me that I have two uncaught
Exceptions in the finally statement apparently originating from the
in.close() and out.close() statements.
import java.io.*;
public class TestOfListOfNumbers {
public static void main(String [] args){
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("d:\\xanadu.txt");
out = new FileOutputStream("out.txt");
int c;
while ((c=in.read()) != -1){
out.write(c);
}
}
catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());
} finally {
if (out != null) {
out.close();
} else {
in.close();
}
}
}
}
While I realize that in calling in.close in the finally statement I am
triggering an IOException why I am not having the same problem in the
program below which Eclipse has no problems with whatsoever.
import java.io.*;
public class TestOfListOfNumbers {
public static void main(String [] args){
PrintWriter out = null;
try {
System.out.println("Entering try statement");
out = new PrintWriter(new
FileWriter("d:\\OutFile.txt"));
for (int i = 0; i < 10; i++)
out.println(i);
}
catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());
} finally {
if (out != null) {
System.out.println("Closing
PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not
open");
}
}
}
}
Hope someone can guide me through.
Best regards
Lars