Home > Java > javaTutorial > The finally block in Java

The finally block in Java

Mary-Kate Olsen
Release: 2024-11-13 02:10:02
Original
624 people have browsed it

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...");
        }
    }
Copy after login
Copy after login

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

Cleaning up resources...
5
Copy after login
Copy after login

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 ...
Copy after login

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();
    }
}
Copy after login

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...");
        }
    }
Copy after login
Copy after login

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
Copy after login
Copy after login

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!

source:dev.to
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template