What is the benefit to use "finally" after try-catch block in java?

Aarath picture Aarath · Apr 2, 2013 · Viewed 24.4k times · Source

The "finally" block is always executed when the try-catch ends, either in case of exception or not. But also every line of code outside and after the try-catch is always executed. So, why should I use the finally statement?

Example:

try {
    //code...
} catch (Exception e) {
    //code...
} finally {
    System.out.println("This line is always printed");
}
System.out.println("Also this line is always printed !! So why to use 'finally'?? ");

Answer

Denys Séguret picture Denys Séguret · Apr 2, 2013

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 catch block lets some throwable pass
  • if it rethrows itself an exception, which is very frequent