Closing a buffered character stream
Hi all!
I have the following
public void somemethod(){
some code
out = new BufferedWriter(new FileWriter(filename));
some code
out.close
}
if an exception occurs, I have to close the stream. But the problem is, how can I close a stream if it had not been opened before. trying to do so would launch a new Exception?
How can I test if my stream is opened before closing it?
try {
out = new BufferedWriter(new FileWriter(filename));
]
catch (SomeException se) {
}
finally {
if (out != null) {
out.close();// it doesn't hurt to close it if it's already closed.
}
}
Even simpler:
void method(String filename) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter(filename));
try {
//...
} finally {
out.close();
}
}
I find the exception handling gets done in the higher level code that calls
routines like this.