Java finally block is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block follows try or catch block.
Finally block in java can be used to put "cleanup" code such as closing a file, closing connection etc.
Let's see the different cases where java finally block can be used.
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{ public static void main(String args[]){ try{ int data=25/5; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } }
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } }
Let's see the java finally example where exception occurs and handled.
public class TestFinallyBlock2{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(ArithmeticException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } }