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!

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

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

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

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]

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool