I\'ve written seven test cases for understanding the behavior of the finally
block. What is the logic behind how finally
works?
pac
Let's start with use case you'll see more often - you have a resource that you must close to avoid a leak.
public void deleteRows(Connection conn) throws SQLException {
Statement statement = conn.createStatement();
try {
statement.execute("DELETE * FROM foo");
} finally {
statement.close();
}
}
In this case, we have to close the statement when we're done, so we don't leak database resources. This will ensure that in the case of an Exception being thrown, we will always close our Statement before the function exits.
try { ... } finally { ... } blocks are meant for ensuring that something will always execute when the method terminates. It's most useful for Exception cases. If you find yourself doing something like this:
public String thisShouldBeRefactored(List foo) {
try {
if(foo == null) {
return null;
} else if(foo.length == 1) {
return foo.get(0);
} else {
return foo.get(1);
}
} finally {
System.out.println("Exiting function!");
}
}
You're not really using finally properly. There is a performance penalty to this. Stick to using it when you have Exception cases that you must clean up from. Try refactoring the above to this:
public String thisShouldBeRefactored(List foo) {
final String result;
if(foo == null) {
result = null;
} else if(foo.length == 1) {
result = foo.get(0);
} else {
result = foo.get(1);
}
System.out.println("Exiting function!");
return result;
}