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 :
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 :
The idea of this
finally
block always being executed is that it's not the case for the first line following the whole blockcatch
block lets some throwable passThe last
System.out.println
(after the finally block) will only be run if the exception thrown in the try block is actuaclly caught with a catch block and if the execution is not interrupted by e.g. a return statement.In your example, the finally block will always be run, but the execution will only continue past the finally block if no
Error
is thrown in the try block (it would not be caught), if noThrowable
is thrown in the catch block and there is no other statement, which will interrupt execution.suppose you are writing in the file and suddenly it creates an exception the how you close the file .then finally help you and also for database transaction finally block helps a lot
finally block's only purpose is to close the resources which you have opened inside try block. resources could be anything like database connections,File writing/reading etc:
This is incorrect. In case of unchecked exceptions (RuntimeException, Error, and their subclasses) code after
finally
will not execute.Take a look at this code
More here