Why can't Analyse Code spot that this should use a finally block?

Is this a case that can be generalized such that close() should be in a finally block? And in this example what benefit is there having code appear outside the try block?

So the catch is unnecessary as the close() can go in a finally block. The only difference it would seem is that the close() executes before successful which would not be the case is successful were moved to the try block.

public class Test {
void doSomeWork() throws Exception {
try {
doWork();
} catch (Exception ex) {
fail();
close();
throw ex;
}
close();
successful();
}

void doWork() throws Exception {

}
void fail() {

}
void successful() {

}
void close() {

}
}

as in

void doSomeWork() throws Exception {
try {
doWork();
successful();
} finally {
close();
}
}

5 comments

Please forget that I called fail() above. Remove fail() altogether from the example for the purpose of the discussion.

0

This sort of thing isn't in product now, other than a very few simple cases like 'duplicate "if" branches'. That said, it's probably worth including. Please submit a JIRA request.

--Dave Griffith

0

Taken into account your request to ignore fail(), what about the "throw ex"?

0

I'm not sure I follow.... throw ex is unnecessary since when replaced with a finally block the exception will still proprogate up.

0

I'll note that the second example calls close() when a Throwable is
thrown, which the first example doesn't.

/Kreiger



Attachment(s):
signature.asc
0

Please sign in to leave a comment.