Extract 002 - try-with-resource mechanisms (syntactic sugar) Java used to omit the try-catch of code in the finally - using IOUtils.closeQuietly (stream) closes the input stream or output elegant stream

Introduction + Advantages of

  1. try-with-resource reference link (recommended to look at, the content is very informative, I did a little supplement) https://www.cnblogs.com/itZhy/p/7636615.html
  2. IOUtils source https://blog.csdn.net/zmx729618/article/details/51888938/

For small chestnuts

pom simple dependence

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

Run 1

public static void main(String[] args) {
    try (FileInputStream inputStream = new FileInputStream(new File("test.txt"))) {
        // 读取到控制台
        System.out.println(inputStream.read());
        // 关闭输入流  , 该方法需要上面的pom依赖
        IOUtils.closeQuietly( inputStream );
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

Results 1

Exception in thread "main" java.lang.RuntimeException: test.txt (系统找不到指定的文件。)
    at Main.main(Main.java:16)
Caused by: java.io.FileNotFoundException: test.txt (系统找不到指定的文件。)
    at java.io.FileInputStream.open0(Native Method)
    at java.io.FileInputStream.open(FileInputStream.java:195)
    at java.io.FileInputStream.<init>(FileInputStream.java:138)
    at Main.main(Main.java:10)

: Can be found IOUtils.closeQuietly( inputStream );close out the stream error information is not thrown out and this is because the null pointer closeQuietly methods judgment is not unusual suppressed.!!

public static void closeQuietly(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (IOException var2) {
            ;
        }

    }

At the same time there is an abnormality suppression

After a look at the anti-compiled code
After a look at the anti-compiled code

public class Main {
    public Main() {
    }

    public static void main(String[] args) {
        try {
            FileInputStream inputStream = new FileInputStream(new File("test.txt"));
            Throwable var2 = null;

            try {
                System.out.println(inputStream.read());
                IOUtils.closeQuietly(inputStream);
            } catch (Throwable var12) {
                var2 = var12;
                throw var12;
            } finally {

                if (inputStream != null) {
                    if (var2 != null) {
                        try {
                            inputStream.close();
                        } catch (Throwable var11) {
                            var2.addSuppressed(var11);
                        }
                    } else {
                        inputStream.close();
                    }
                }

            }

        } catch (IOException var14) {
            throw new RuntimeException(var14.getMessage(), var14);
        }
    }
}

Decompile the code, you may notice that there is a special code to handle the exception:

var2.addSuppressed(var11);
  • This is another knowledge try-with-resource involving grammar, called abnormal suppression. When external resources are processed (eg read or write), if you encounter an exception, and in the subsequent process of closing external resources, has suffered abnormal, then you will catch to be encountered during the processing of external resources abnormal, encountered in the closed resource error is "suppressed", but not discarded by methods getSuppressed abnormality, the abnormality can be extracted is suppressed.
  • try-with-resource, if the processing and closing of external resources to external resources have suffered abnormal, "abnormal closed" will be suppressed, "Handling exceptions" will be thrown, but "Off exception" is not lost, but stored in the exception list the suppressed "exception handling" of.

Abnormal release inhibition

Additional pom

 <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>
        <!-- log -->
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.21</version>
        </dependency>

Add code that uses e.getSuppressed (); get to pent-up did not throw an exception

@Slf4j
public class Main {
    public static void main(String[] args) {
        try (FileInputStream inputStream = new FileInputStream(new File("test.txt"))) {
            // 读取到控制台
            System.out.println(inputStream.read());
            // 关闭输入流
            IOUtils.closeQuietly( inputStream );
        } catch (IOException e) {
            Throwable[] suppressed = e.getSuppressed();
            for (Throwable throwable : suppressed) {
                log.error("", throwable);
            }
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}

Create a set of sample

对外部资源的处理和对外部资源的关闭均遭遇了异常, 太难了, 造不出来.....................
如果你可以的, 麻烦在下面贴一下`英雄帖`!

Note compiled version of the problem, at least JDK5, please specify jdk compiled version in the pom

pom can be specified

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>8</source>
                    <target>8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

Goof off at work writing blog, the evening had to work overtime ~ ~

Guess you like

Origin www.cnblogs.com/zhazhaacmer/p/12163394.html