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!

Java'splatformindependencemeansdeveloperscanwritecodeonceandrunitonanydevicewithoutrecompiling.ThisisachievedthroughtheJavaVirtualMachine(JVM),whichtranslatesbytecodeintomachine-specificinstructions,allowinguniversalcompatibilityacrossplatforms.Howev

To set up the JVM, you need to follow the following steps: 1) Download and install the JDK, 2) Set environment variables, 3) Verify the installation, 4) Set the IDE, 5) Test the runner program. Setting up a JVM is not just about making it work, it also involves optimizing memory allocation, garbage collection, performance tuning, and error handling to ensure optimal operation.

ToensureJavaplatformindependence,followthesesteps:1)CompileandrunyourapplicationonmultipleplatformsusingdifferentOSandJVMversions.2)UtilizeCI/CDpipelineslikeJenkinsorGitHubActionsforautomatedcross-platformtesting.3)Usecross-platformtestingframeworkss

Javastandsoutinmoderndevelopmentduetoitsrobustfeatureslikelambdaexpressions,streams,andenhancedconcurrencysupport.1)Lambdaexpressionssimplifyfunctionalprogramming,makingcodemoreconciseandreadable.2)Streamsenableefficientdataprocessingwithoperationsli

The core features of Java include platform independence, object-oriented design and a rich standard library. 1) Object-oriented design makes the code more flexible and maintainable through polymorphic features. 2) The garbage collection mechanism liberates the memory management burden of developers, but it needs to be optimized to avoid performance problems. 3) The standard library provides powerful tools from collections to networks, but data structures should be selected carefully to keep the code concise.

Yes,Javacanruneverywhereduetoits"WriteOnce,RunAnywhere"philosophy.1)Javacodeiscompiledintoplatform-independentbytecode.2)TheJavaVirtualMachine(JVM)interpretsorcompilesthisbytecodeintomachine-specificinstructionsatruntime,allowingthesameJava

JDKincludestoolsfordevelopingandcompilingJavacode,whileJVMrunsthecompiledbytecode.1)JDKcontainsJRE,compiler,andutilities.2)JVMmanagesbytecodeexecutionandsupports"writeonce,runanywhere."3)UseJDKfordevelopmentandJREforrunningapplications.

Key features of Java include: 1) object-oriented design, 2) platform independence, 3) garbage collection mechanism, 4) rich libraries and frameworks, 5) concurrency support, 6) exception handling, 7) continuous evolution. These features of Java make it a powerful tool for developing efficient and maintainable software.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools
