Java finally block is a block used to execute important code such as closing the connection, etc. Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of whether the exception occurs or not.
Few Important points regarding finally block
1. A finally block must be associated with a try block, you cannot use finally without a try block. You should place those statements in this block that must be executed always.
2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient for exception handling, however, if you place a finally block then it will always run after the execution of the try block.
3. In normal cases when there is no exception in the try block then the finally block is executed after the try block. However, if an exception occurs then the catch block is executed before finally block.
4. An exception in the finally block, behaves exactly like any other exception.
Syntax of Finally block
try {//Statements that may cause an exception}catch {//Handling exception}finally {//Statements to be executed}
Example Case 1: When exception does not occur.
Java
package com.prac;public class FinallyBlockCase1 {public static void main(String args[]) {try {int data = 25 / 5;System.out.println(data);} catch (Exception e) {System.out.println(e);} finally {System.out.println("finally blockis always executed");}}}
Output
5 finally block is always executed
Example Case 2: When an exception occurs and is caught by the catch block.
Java
package com.prac;public class FinallyBlockCase2 {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 blockis always executed");}}}
Output
java.lang.ArithmeticException: / by zero finally block is always executed
Example Case 3: When an exception occurs and is not caught by the catch block.
Java
package com.prac;public class FinallyBlockCase3 {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 blockis always executed");}}}
Output
finally block is always executed Exception in thread "main" java.lang.ArithmeticException: / by zero at com.prac.FinallyBlockCase3.main(FinallyBlockCase3.java:6)
Exception Handling Using Throws keyword
Java try/ catch block exception handling
Java catches Multiple Exceptions
Exception Handling Using Throw keyword
Java nested try block exception handling
Java custom exception handling
No comments:
Post a Comment