The try-finally and try-catch-finally statements

suggest change

The try...catch...finally statement combines exception handling with clean-up code. The finally block contains code that will be executed in all circumstances. This makes them suitable for resource management, and other kinds of cleanup.

Try-finally

Here is an example of the simpler (try...finally) form:

try {
    doSomething();  
} finally {
    cleanUp();
}

The behavior of the try...finally is as follows:

- The code in the `finally` block is executed.
- If the `finally` block throws an exception, that exception is propagated.
- Otherwise, control passes to the next statement after the `try...finally`.
- The code in the `finally` block is executed.
- If the `finally` block throws an exception, that exception is propagated.
- Otherwise, the original exception continues to propagate.

The code within finally block will always be executed. (The only exceptions are if System.exit(int) is called, or if the JVM panics.) Thus a finally block is the correct place code that always needs to be executed; e.g. closing files and other resources or releasing locks.

try-catch-finally

Our second example shows how catch and finally can be used together. It also illustrates that cleaning up resources is not straightforward.

// This code snippet writes the first line of a file to a string
String result = null;
Reader reader = null;
try {
    reader = new BufferedReader(new FileReader(fileName));
    result = reader.readLine();
} catch (IOException ex) {
    Logger.getLogger.warn("Unexpected IO error", ex);  // logging the exception
} finally {
    if (reader != null) {
        try {
            reader.close();
        } catch (IOException ex) {
            // ignore / discard this exception
        }
    }
}

The complete set of (hypothetical) behaviors of try...catch...finally in this example are too complicated to describe here. The simple version is that the code in the finally block will always be executed.

Looking at this from the perspective of resource management:

Java 7 and later provide an alternative try-with-resources syntax which significantly simplifies resource clean-up.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Exceptions:
* The try-finally and try-catch-finally statements

Table Of Contents
3 Exceptions
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap