Java exception handling Overview - Advanced

preface

Java exception handling Overview - Fundamentals This paper introduces some basic operations of Java exception handling. This paper introduces some advanced operations of exception handling!

Try with resources statement

When we operate on some resources, we often have a fixed expression:

  • Open resource in try
  • Close resource in finally

For example, the following program:

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

The program example reads the first line from a file. It uses the BufferedReader instance to read data from the file, which is a resource that must be closed after the program completes.

Before Java SE 7, the operation of resources can only be realized through the cumbersome code above, that is, use the finally block to ensure that the resources are closed.

However, after Java SE 7, you can use the try with resources statement without explicitly closing the resources in the finally block. No matter whether the try statement is completed normally or blocked abnormally, the resources will be closed automatically! It is written as follows:

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

You will find that the try statement has a pair of parentheses. The parentheses can be filled with expressions, which are actually declarations of resources.

Multi resource processing

At this time, you may ask, what if I have multiple resources to declare in the try?

It can be divided by semicolons.

Like this:

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

After entering the execution of the try code block, whether normal or abnormal, when the contemporary code block terminates, the close methods of BufferedWriter and ZipFile will be called in turn, so as to automatically close the resources.

Note: the call order of the close method of the resource is opposite to its creation order. It's easy to understand. Imagine putting all the resources involved in the try into a narrow pool in turn. It's like a queue. First in, then out, first created, and finally closed the resources.

Principle analysis

At this point, you may ask, why are the resources in the example automatically closed?

The most direct reason is that they all have methods to close resources.

The fundamental reason is that they all implement the interface of autoclosable and have the ability of close.

As the name implies, autoclosable also indicates that the objects that implement its interface have the ability to close themselves automatically. Looking at the notes, since 1.7, you can also know that this capability really starts with Java 7.

So, if you have custom resources, remember to implement autoclosable.

Tags: Java Back-end

Posted on Fri, 12 Nov 2021 21:26:49 -0500 by JakeTheSnake3.0