finally Block in JavaLast Updated : 13 Jan 2026 In Java, the finally block is used to execute important code such as closing files or releasing resources, regardless of whether an exception occurs or not. In this chapter, we will learn about the finally block along with the examples. What is the Finally Block in Java?The finally block is a block of code that always executes after a try block, whether an exception is thrown or not. The finally block is useful when you want to cleanup activities or free the resources, like closing files, streams, or database connections. Key PointsThe following key points of the finally block are as follows:
Flow DiagramThe following images shows the flow diagram (working) of the finally block: ![]() Note: If we do not handle the exception before terminating the program, the JVM executes the finally block (if any). Example of Using Finally BlockThe following example demonstrates how a finally block is executed whether an exception occurs or not: Output: Exception caught: java.lang.ArithmeticException: / by zero Finally block executed: Cleanup code runs here. Rest of the program continues... Usage of the finally BlockLet's see different scenarios where a finally block can be used. Case 1: When No Exception OccursIf the code in the try block executes normally without throwing an exception, the finally block is still executed. The following example demonstrates the execution of the finally block when no exception occurs: Output: 5 Finally block is always executed rest of the code... Case 2: When an Exception Occurs but Is Not HandledIf an exception occurs but the catch block cannot handle it, the finally block is still executed before the program terminates abnormally. The following example demonstrates that the finally block is executed even if an exception occurs but is not handled by the catch block: Output: Inside the try block Finally block is always executed Runtime Error: Exception in thread "main" java.lang.ArithmeticException: / by zero at Main.main(Main.java:8) Case 3: When an Exception Occurs and Is HandledIf an exception occurs and the catch block handles it, the finally block is executed afterward, and the rest of the program continues normally. The following example demonstrates the execution of the finally block when an exception occurs and is handled by the catch block: Output: Inside the try block Exception handled java.lang.ArithmeticException: / by zero Finally block is always executed rest of the code... Rule: For each try block, there can be zero or more catch blocks, but the finally block will be one. Note: The finally block will not execute if the program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort). Next TopicJava-throw-exception |
We request you to subscribe our newsletter for upcoming updates.