추출 002 - 시도 -과 - 자원 메커니즘은 (문법적) 자바는 마지막으로 코드의 시도 - 캐치를 생략하는 데 사용 - 사용 IOUtils.closeQuietly (스트림) 입력 스트림 또는 출력 우아한 스트림을 닫습니다

소개 + 장점

  1. 시도 -과 - 자원 참조 링크를 (내용이 매우 유익 볼 것을 권장합니다, 나는 약간의 보충을했다) https://www.cnblogs.com/itZhy/p/7636615.html
  2. IOUtils 소스 https://blog.csdn.net/zmx729618/article/details/51888938/

작은 밤을 위해

치어 간단한 의존성

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

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

결과 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)

: 찾을 수 IOUtils.closeQuietly( inputStream );스트림 오류 정보를 밖으로 가까운 밖으로 던져되지 않고 널 포인터 closeQuietly 방법 판단은 드문 일이 아니다 억제 때문입니다!.

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

    }

동시에 이상 억제가

안티 - 컴파일 된 코드를 살펴 후
안티 - 컴파일 된 코드를 살펴 후

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

코드 컴파일, 당신은 예외를 처리하는 특수 코드가 있음을 알 수 있습니다 :

var2.addSuppressed(var11);
  • 이것은 비정상적인 억제라는 문법을 포함하는 또 다른 지식 시도 -과 - 자원이다. 사용자가 예외를 발생하고, 외부 자원을 폐쇄하는 후속 공정에서 이상 겪었다 경우 외부 자원이 처리 될 때 (예를 들어 판독 또는 기입), 그 후에는 외부 자원의 프로세싱 중에 발생 될 잡을 폐 자원 에러 발생, 이상이 "억제"하지만 이상을 getSuppressed 방법에 의해 폐기되지 않고, 추출 할 수있는 이상이 억제된다.
  • 시도 -과 - 자원, 외부 자원에 대한 외부 자원의 마감 처리 및 비정상적인 고통을 경우, "비정상적인 폐쇄"억제 할 것 "예외 처리"가 발생합니다, 그러나 "예외 끄기"손실되지 않습니다, 하지만, 예외 목록의 억제 "예외 처리"를 저장.

비정상적인 방출 억제

가점 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>

용도는 () e.getSuppressed 것을 코드를 추가, 예외를 발생하지 않았다 갇힌에 도착

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

샘플 세트를 만들기

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

문제의 참고 컴파일 된 버전은, 적어도 JDK5는 치어의 컴파일 된 버전을 JDK 지정하세요

치어을 지정할 수 있습니다

    <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>

작품 쓰기 블로그에서 떨어져 노는, 저녁이 작업 초과 근무로했다 ~ ~

추천

출처www.cnblogs.com/zhazhaacmer/p/12163394.html