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'?? ");
A Finally block is useful for running any code that must execute even if there is an exception. Control is passed to the Finally block regardless of how the Try...Catch block exits. The code in a Finally block runs even if your code encounters a Return statement in a Try or Catch block.
Syntax. The code which is prone to exceptions is placed in the try block. When an exception occurs, that exception occurred is handled by catch block associated with it. Every try block should be immediately followed either by a catch block or finally block.
@barth When there's no catch block the exception thrown in finally will be executed before any exception in the try block. So If there are two exceptions one in try and one in finally the only exception that will be thrown is the one in finally .
Nope, not at all. Its not mandatory to put catch after try block, unless and until the try block is followed by a finally block. Just remember one thing, after try, a catch or a finally or both can work.
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 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 no Throwable
is thrown in the catch block and there is no other statement, which will interrupt execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With