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'?? ");
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
catch
block lets some throwable pass