The most useful case is when you need to release some resources :
InputStream is = ...
try {
//code...
} catch (Exception e) {
//code...
} finally {
is.close();
}
More generally, you use it when you want to be sure your code is executed at the end, even if there was an exception during execution :
long startTime = System.currentTimeMillis();
try {
//code...
} catch (Exception e) {
//code...
} finally {
long endTime = System.currentTimeMillis();
System.out.println("Operation took " + (endTime-startTime) + " ms");
}
The idea of this finally block always being executed is that it’s not the case for the first line following the whole block
- if the
catchblock lets some throwable pass - if it rethrows itself an exception, which is very frequent