In this section we will discuss about finally block in java. Finally block always execute when try block exits. Finally is a block of code that execute after try/catch block
Finally in java
In this section we will discuss about finally block in java. Finally block always execute when try block exits. Finally is a block of code that execute after try/catch block. finally will execute whether exception is thrown or not. When exception is thrown finally will execute even if no catches statement matches the exception. Besides exception handling, finally is also used in file closing and freeing up any other resources, when a method is about to return to the caller from inside try/catch block through a return statement and finally clause is executed just before methods returns. The finally block is mainly used to perform some important tasks such as closing connection, stream etc. Putting a clean up code inside a finally block is a good practice.
In the example 1, finally block is always executed, whether exception has occurred or not, so while dividing 5 by 0 will throw an exception, it is handled by catch block but finally block is executed always.
Example 1 : Program in case exception Occurs
public class FinallyBlock { public static void main(String args[]) { try { int a=5/0; } catch(ArithmeticException e) { System.out.println(e); } finally { System.out.println("Inside finally block"); } } }
Output : java.lang.ArithmeticException: /
by zero
Inside finally block
Example 2 : Program in case exception Does Not Occur
public class FinallyBlock { public static void main(String args[]) { try { int a=5/2; } catch(ArithmeticException e) { System.out.println(e); } finally { System.out.println("Inside finally block"); } } }
Output : value of a = 2
Inside finally block