search
HomeJavajavaTutorialThe finally block in Java

El bloque finally en Java

When working with exceptions in Java, it is common to find the need to use a try-catch block to handle them and not just delegate their handling to whoever calls this part of the code. However, sometimes it is necessary to perform certain actions, regardless of whether an exception was thrown or not, or whether the program execution flow completed successfully, for example, closing a file, a connection to a database, etc. .

For these cases the finally block is used. This block is placed after the catch block, or even after the try block if a catch block is not used. The code placed inside the finally block will be executed in two scenarios:

  • When the try block ends and no exception has been thrown.
  • When an exception occurs, so the execution flow will be interrupted and the catch block will be executed.

Example 1

Let's consider a divide method that receives two integers and returns the result of the division between them. This uses a try-catch block to handle the exception that is thrown when attempting to divide by zero, as well as a finally block to print a message indicating that resources are being cleaned.

public static int divide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
            throw e;
        } finally {
            System.out.println("Cleaning up resources...");
        }
    }

By calling the divide method with the values ​​10 and 2, the following output will be obtained:

Cleaning up resources...
5

As we can see, no exception was thrown, so the method returned the result of the division and the finally block was executed, although the output of the finally block is shown first. On the other hand, if the divide method is called with the values ​​10 and 0, the following output will be obtained:

Error: / by zero
Cleaning up resources...
Exception in thread "main" java.lang.ArithmeticException: / by zero ...

In this case, an exception was thrown, so the execution flow was interrupted and the catch block was executed, but before throwing the exception again, the finally block was executed. In both examples we have seen that the finally block is always executed, regardless of the result obtained.

Example 2

The main use of the finally block is to free resources that have been used in the try block, such as closing a file, a database connection, or a network connection. To exemplify this, let's consider a readFile method that reads the contents of a file and returns the first line. This uses a try-catch block to handle the exception that is thrown if the file cannot be read, as well as a finally block to close the file.

public static String readFile() throws IOException {
    FileReader reader = null;
    try {
        reader = new FileReader("file.txt");
        BufferedReader buffer = new BufferedReader(reader);
        return buffer.readLine();
    } catch (IOException e) {
        System.out.println("Error: " + e.getMessage());
        throw new RuntimeException(e);
    } finally {
        if (reader != null) reader.close();
    }
}

In case the readFile method is executed and the file cannot be read, the following output will be obtained:

public static int divide(int a, int b) {
        try {
            return a / b;
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
            throw e;
        } finally {
            System.out.println("Cleaning up resources...");
        }
    }

As we can see, an exception was thrown, so the execution flow was interrupted and the catch block was executed, but before throwing the exception again, the finally block was executed to close the file. On the other hand, if a file.txt file is created with the content Hello world! and the readFile method is called, the following output will be obtained, without throwing any exception:

Cleaning up resources...
5

Some aspects to take into account in this example are:

  • The reader variable was declared outside the try block so that it can be accessed from the finally block, that is, it is within the scope of both blocks.
  • Checked if the reader variable is different from null before trying to close the file, because if the file cannot be opened, this variable will remain null and will throw an exception when trying to close it.
  • The possible exception that the close method can throw when trying to close the file within the finally block is not handled and is propagated in the method signature, in case you want to handle it, you can wrap it in a try-catch block inside the finally block.

Conclusion

The use of finally within Java has become so common that the language itself has an alternative that allows us to simplify resource management, the try-with-resources block. This block is responsible for closing the resources automatically at the end of their use, so it is not necessary to use a finally block to release the resources. However, it is important to note that the finally block is still useful in certain cases and both options can be used together.

The above is the detailed content of The finally block in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool