user219882
user219882

Reputation: 15844

Proper way to close files and propagate exception in the same time

I want to safely close resources and than propagate an exception. So far I came up with two solutions.

Solution 1

FileObject sourceDir = null;
FileObject targetDir = null;
BufferedWriter bw = null;
BufferedReader br = null;

try {
    // R/W operation with files
} finally {
    // close sourceDir, targetDir, br, bw
}

Solution 2

FileObject sourceDir = null;
FileObject targetDir = null;
BufferedWriter bw = null;
BufferedReader br = null;

try {
    // R/W operation with files
} catch (IOException e) {
    throw e;
} finally {
    // close sourceDir, targetDir, br, bw
}

I don't like throw e in the second solution but try-finally seems a little bit unusual to me so I'm not sure which one of these I should use. Or is there any better way how to do it?

Upvotes: 0

Views: 98

Answers (2)

Boris Pavlović
Boris Pavlović

Reputation: 64650

Second solution may be useful if you want to log the exception and/or wrap it in a runtime exception and throw it.

Upvotes: 2

DerMike
DerMike

Reputation: 16200

Option 1 is exacly right. try ... finally is usually used for that.

You might even put a return into your try block and Java will process your finally and return then.

Upvotes: 1

Related Questions