Learning Resources
 

Try---catch---finally blocks

Catching and Handling Exceptions

This section describes how to use the three exception handler components — the try, catch, and finallyblocks — to write an exception handler. Then, the try-with-resources statement, introduced in Java SE 7, is explained. The try-with-resources statement is particularly suited to situations that use Closeableresources, such as streams.

The last part of this section walks through an example and analyzes what occurs during various scenarios.

The following example defines and implements a class named ListOfNumbers. When constructed, ListOfNumberscreates an ArrayListthat contains 10 Integerelements with sequential values 0 through 9. The ListOfNumbersclass also defines a method named writeList, which writes the list of numbers into a text file called OutFile.txt. This example uses output classes defined in java.io, which are covered in ListOfNumbersclass, the compiler prints an error message about the exception thrown by the FileWriterconstructor. However, it does not display an error message about the exception thrown by get. The reason is that the exception thrown by the constructor, IOException, is a checked exception, and the one thrown by the getmethod, IndexOutOfBoundsException, is an unchecked exception.

Now that you're familiar with the ListOfNumbersclass and where the exceptions can be thrown within it, you're ready to write exception handlers to catch and handle those exceptions.

The try Block

The first step in constructing an exception handler is to enclose the code that might throw an exception within a tryblock. In general, a tryblock looks like the following:

try {
    code
}
catch and finally blocks . . .

The segment in the example labeled codecontains one or more legal lines of code that could throw an exception. (The catchand finallyblocks are explained in the next two subsections.)

To construct an exception handler for the writeListmethod from the ListOfNumbersclass, enclose the exception-throwing statements of the writeListmethod within a tryblock. There is more than one way to do this. You can put each line of code that might throw an exception within its own tryblock and provide separate exception handlers for each. Or, you can put all the writeListcode within a single tryblock and associate multiple handlers with it. The following listing uses one tryblock for the entire method because the code in question is very short.

private List list;
private static final int SIZE = 10;

PrintWriter out = null;

try {
    System.out.println("Entered try statement");
    out = new PrintWriter(new FileWriter("OutFile.txt"));
    for (int i = 0; i < SIZE; i++) {
        out.println("Value at: " + i + " = " + list.get(i));
    }
}
catch and finally statements . . .

If an exception occurs within the tryblock, that exception is handled by an exception handler associated with it. To associate an exception handler with a tryblock, you must put a catchblock after it; the next section, AutoCloseableand Closeableinterfaces for a list of classes that implement either of these interfaces. The Closeableinterface extends the AutoCloseableinterface. The closemethod of the Closeableinterface throws exceptions of type IOExceptionwhile the closemethod of the AutoCloseableinterface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseableinterface can override this behavior of the closemethod to throw specialized exceptions, such as IOException, or no exception at all.

The catch Blocks

You associate exception handlers with a tryblock by providing one or more catchblocks directly after the tryblock. No code can be between the end of the tryblock and the beginning of the first catchblock.

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

Each catchblock is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwableclass. The handler can refer to the exception with name.

The catchblock contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionTypematches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument.

The following are two exception handlers for the writeListmethod — one for two types of checked exceptions that can be thrown within the trystatement:

try {

} catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException: " + e.getMessage());
    throw new SampleException(e);

} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}

Both handlers print an error message. The second handler does nothing else. By catching any IOExceptionthat's not caught by the first handler, it allows the program to continue executing.

The first handler, in addition to printing a message, throws a user-defined exception. (Throwing exceptions is covered in detail later in this chapter in the AutoCloseableand Closeableinterfaces for a list of classes that implement either of these interfaces. The Closeableinterface extends the AutoCloseableinterface. The closemethod of the Closeableinterface throws exceptions of type IOExceptionwhile the closemethod of the AutoCloseableinterface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseableinterface can override this behavior of the closemethod to throw specialized exceptions, such as IOException, or no exception at all.

The finally Block

The finallyblock always executes when the tryblock exits. This ensures that the finallyblock is executed even if an unexpected exception occurs. But finallyis useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finallyblock is always a good practice, even when no exceptions are anticipated.


Note: If the JVM exits while the tryor catchcode is being executed, then the finallyblock may not execute. Likewise, if the thread executing the tryor catchcode is interrupted or killed, the finallyblock may not execute even though the application as a whole continues.

The tryblock of the writeListmethod that you've been working with here opens a PrintWriter. The program should close that stream before exiting the writeListmethod. This poses a somewhat complicated problem because writeList's tryblock can exit in one of three ways.

  1. The new FileWriterstatement fails and throws an IOException.
  2. The vector.elementAt(i)statement fails and throws an ArrayIndexOutOfBoundsException.
  3. Everything succeeds and the tryblock exits normally.

The runtime system always executes the statements within the finallyblock regardless of what happens within the tryblock. So it's the perfect place to perform cleanup.

The following finallyblock for the writeListmethod cleans up and then closes the PrintWriter.

finally {
    if (out != null) { 
        System.out.println("Closing PrintWriter");
        out.close(); 
    } else { 
        System.out.println("PrintWriter not open");
    } 
} 

In the writeListexample, you could provide for cleanup without the intervention of a finallyblock. For example, you could put the code to close the PrintWriterat the end of the tryblock and again within the exception handler for ArrayIndexOutOfBoundsException, as follows.

try {
    
    // Don't do this; it duplicates code. 
    out.close();
    
} catch (FileNotFoundException e) {
    // Don't do this; it duplicates code.
    out.close();

    System.err.println("Caught FileNotFoundException: " + e.getMessage());
    throw new RuntimeException(e);
    
} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}

However, this duplicates code, thus making the code difficult to read and error-prone should you modify it later. For example, if you add code that can throw a new type of exception to the tryblock, you have to remember to close the PrintWriterwithin the new exception handler.


Important: The finallyblock is a key tool for preventing resource leaks. When closing a file or otherwise recovering resources, place the code in a finallyblock to ensure that resource is always recovered.

If you are using Java SE 7 or later, consider using the try-with-resources statement in these situations, which automatically releases system resources when no longer needed. The next section has more information.

The try-with-resources Statement

The try-with-resources statement is a trystatement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReaderto read data from the file. BufferedReaderis a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the trykeyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReaderinstance is declared in a try-with-resource statement, it will be closed regardless of whether the trystatement completes normally or abruptly (as a result of the method BufferedReader.readLinethrowing an IOException).

Prior to Java SE 7, you can use a finallyblock to ensure that a resource is closed regardless of whether the trystatement completes normally or abruptly. The following example uses a finallyblock instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

However, in this example, if the methods readLineand closeboth throw exceptions, then the method readFirstLineFromFileWithFinallyBlockthrows the exception thrown from the finallyblock; the exception thrown from the tryblock is suppressed. In contrast, in the example readFirstLineFromFile, if exceptions are thrown from both the tryblock and the try-with-resources statement, then the method readFirstLineFromFilethrows the exception thrown from the tryblock; the exception thrown from the try-with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

You may declare one or more resources in a try-with-resources statement. The following example retrieves the names of the files packaged in the zip file zipFileNameand creates a text file that contains the names of these files:

public static void writeToFileZipFileContents(String zipFileName,
                                           String outputFileName)
                                           throws java.io.IOException {

    java.nio.charset.Charset charset =
         java.nio.charset.StandardCharsets.US_ASCII;
    java.nio.file.Path outputFilePath =
         java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with 
    // try-with-resources statement

    try (
        java.util.zip.ZipFile zf =
             new java.util.zip.ZipFile(zipFileName);
        java.io.BufferedWriter writer = 
            java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {
        // Enumerate each entry
        for (java.util.Enumeration entries =
                                zf.entries(); entries.hasMoreElements();) {
            // Get the entry name and write it to the output file
            String newLine = System.getProperty("line.separator");
            String zipEntryName =
                 ((java.util.zip.ZipEntry)entries.nextElement()).getName() +
                 newLine;
            writer.write(zipEntryName, 0, zipEntryName.length());
        }
    }
}

In this example, the try-with-resources statement contains two declarations that are separated by a semicolon: ZipFileand BufferedWriter. When the block of code that directly follows it terminates, either normally or because of an exception, the closemethods of the BufferedWriterand ZipFileobjects are automatically called in this order. Note that the closemethods of resources are called in the opposite order of their creation.

The following example uses a try-with-resources statement to automatically close a java.sql.Statementobject:

public static void viewTable(Connection con) throws SQLException {

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES";

    try (Statement stmt = con.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);

        while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
            int sales = rs.getInt("SALES");
            int total = rs.getInt("TOTAL");

            System.out.println(coffeeName + ", " + supplierID + ", " + 
                               price + ", " + sales + ", " + total);
        }
    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    }
}

The resource java.sql.Statementused in this example is part of the JDBC 4.1 and later API.

Note: A try-with-resources statement can have catchand finallyblocks just like an ordinary trystatement. In a try-with-resources statement, any catchor finallyblock is run after the resources declared have been closed.

Suppressed Exceptions

An exception can be thrown from the block of code associated with the try-with-resources statement. In the example writeToFileZipFileContents, an exception can be thrown from the tryblock, and up to two exceptions can be thrown from the try-with-resources statement when it tries to close the ZipFileand BufferedWriterobjects. If an exception is thrown from the tryblock and one or more exceptions are thrown from the try-with-resources statement, then those exceptions thrown from the try-with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContentsmethod. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressedmethod from the exception thrown by the tryblock.

Classes That Implement the AutoCloseable or Closeable Interface

See the Javadoc of the AutoCloseableand Closeableinterfaces for a list of classes that implement either of these interfaces. The Closeableinterface extends the AutoCloseableinterface. The closemethod of the Closeableinterface throws exceptions of type IOExceptionwhile the closemethod of the AutoCloseableinterface throws exceptions of type Exception. Consequently, subclasses of the AutoCloseableinterface can override this behavior of the closemethod to throw specialized exceptions, such as IOException, or no exception at all.

--Oracle