What is the benefit to use “finally” after try-catch block in java? [closed]

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)