Java finally blockJava 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 the exception occurs or not. The finally block follows the try-catch block. Flowchart of finally blockNote: If you don't handle the exception, before terminating the program, JVM executes finally block (if any).Why use Java finally block?
Usage of Java finallyLet's see the different cases where Java finally block can be used. Case 1: When an exception does not occurLet's see the below example where the Java program does not throw any exception, and the finally block is executed after the try block. TestFinallyBlock.java Output: Case 2: When an exception occurr but not handled by the catch blockLet's see the the fillowing example. Here, the code throws an exception however the catch block cannot handle it. Despite this, the finally block is executed after the try block and then the program terminates abnormally. TestFinallyBlock1.java Output: Case 3: When an exception occurs and is handled by the catch blockExample: Let's see the following example where the Java code throws an exception and the catch block handles the exception. Later the finally block is executed after the try-catch block. Further, the rest of the code is also executed normally. TestFinallyBlock2.java Output: Rule: For each try block there can be zero or more catch blocks, but only one finally block.Note: The finally block will not be executed if the program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort).Next TopicJava Throw Keyword |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India