Finally Block in Java: Usage & Practical Examples

Updated on October 8, 2024

Article Outline

The finally block plays an automatic role in exception handling in Java language. That way, a piece of code will execute no matter what happens when the try-or-catch blocks run. The most common thing you will use this for is to release resources like file handles, database connections, or sockets. In this article, We will explain a finally block in Java.

Introduction to finally Block in Java

The finally block in Java is part of the exception handling mechanism that ensures certain code will always run, regardless of whether an exception occurs in the try-and-catch block or not. This block is used to execute import source code, such as closing resources, cleaning up memory, or performing other tasks that need to be done after executing the try-or-catch blocks.

 

Program

class Main{ public static void main(String args[]){ try{ int data = 10/0 ; System.out.println(data); }catch(ArithmeticException e){ System.out.println("Exception Caught"+e); } finally { System.out.println("This code will always execute"); } } }

Output

Exception Caughtjava.lang.ArithmeticException: / by zero This code will always execute
*Image
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure

Syntax of finally block

The finally block follows a try block or a try-catch block, and it looks like this.

try { // Code that may throw an exception } catch (Exception e) { // Handling exception } finally { // Code that will always execute }

Why Use finally in Java?

Finally, a block in Java is usually used to ensure that some specific piece of source code is executed whenever the Java codes are supposed to be from the preceding try block, which always executes, even if an exception occurs. This is very useful for tasks where you need to handle resource cleanup and perform some cleanup; otherwise, you will have resource leaks, and the program will not be stable. An exception occurs within the preceding try block. This is especially useful for tasks such as life resource cleanup,  which must be completed to avoid resource leaks and maintain program stability.

Reasons to use finally in Java

 

  • Reasons Management: Once you’ve finished with resources such as file streams, sockets, or database connections, you must release them. The final block ensures these resources are closed properly, even if an exception occurs during processing.

 

  • Guaranteed Code Execution: The finally block always executes after the try block, whether an exception is thrown or not. This guarantees that the cleanup code is executed and ensures consistent behavior.

 

  • Error Handling and Cleanup: We can also use the finally block to perform cleanup actions, such as releasing memory or resetting variable states, regardless of whether the program can handle the exception.

 

Also Read: Types of Exceptions in Java

 

Program

import java.io.File ; import java.io.FileNotFoundException; import java.util.Scanner; class Main{ public static void main(String args[]){ Scanner scanner  = null ; try{ File file = new File("wrodig.txt") ; scanner = new Scanner(file) ; while(scanner.hasNextLine()){ String line =  scanner.nextLine(); System.out.println(line); } }catch(FileNotFoundException e){ System.out.println("File is not found"+e.getMessage()); }finally{ if (scanner != null){ scanner.close(); System.out.println("Scanner closed successfully"); } } } }

Output

File is not foundwrodig.txt (The system cannot find the file specified)

Usage of finally block

Let’s see the different usage examples of finally block in java.

Case 1: When an exception does not occur

Java program does not throw any exception, and the finally block is executed after the try block.

Program

class Main{ public static void main(String args[]){ try{ int divide = 25/ 2 ; System.out.println(divide); }catch(NullPointerException e){ System.out.println(e.getMessage()) ; }finally{ System.out.println("This block always execute"); } } }

Output

12 This block always execute

Case 2: When an exception occurs but is not handled by the catch block

 

In the following example, Code throws an exception. However, the catch block cannot handle it. This final block is executed after the try block, and the program terminates abnormally.

 

Program

class Main{ public static void main(String args[]){ try{ int divide = 2 /0 ; System.out.println(divide); }catch(NullPointerException e){ System.out.println(e.getMessage()); }finally{ System.out.println("finally block is always executed"); } } }

Output

finally block is always executed Exception in thread "main" java.lang.ArithmeticException: / by zero

Case 3: When an exception occurs, it is handled by the catch block

In this scenario, the program throws an exception, but handled by the catch block executes after the catch block.

Program

import java.io.* ; class Main{ public static void main(String args[]){ try{ System.out.println(34/0) ; }catch(ArithmeticException e){ System.out.println(); }finally{ System.out.println("this block always execute"); } } }

Output

this block always execute

How finally Works with try-catch

The finally block is executed after the try block, regardless of whether an exception is thrown. If there is a catch block, it finally runs after it.

Let’s see how it finally works.

 

  • If there is not exception occurs in the try block, the finally block runs after the try.
  • If an exception occurs and is caught by the catch block, the finally block runs after the catch.
  • If an exception occurs and is not caught, the finally block will still execute before the program terminates.

Conclusion

In this article, we learn about the last block in Java. Resource and cleanup management and completion of tasks up to the exception are crucial. It is used to try and catch blocks to ensure that if something goes wrong, your important source code, like closing files and releasing resources, doesn’t get shot down the toilet. Finally, the block always runs after the try block, except for forced termination.  Finally, it makes your source code more robust and reliable by ensuring that cleanup tasks are always done.

FAQs
The finally block executes code after a try block, regardless of whether an exception is thrown. It is typically used for resource cleanup, such as closing files or cleaning the locks.
Yes, the finally block will almost always execute, even if an exception is thrown in the try block. However, rare exceptions exist, such as when System.exit() is called or the JVM (Java Virtual Machine) crashes.
Yes, a finally block can be used with just a try block, without any catch block. The syntax try-finally is common for executing code that must always run, like resource cleanup.
If the try block contains a return statement, the finally block will still execute before the method actually returns.
No, you cannot have multiple finally blocks. A try block can be followed by only one finally block.

Updated on October 8, 2024

Link
left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved