1Z0-809复习 第6章 Exception and Assertion

Exceptions and Assertions

Reviewing Exceptions

Exceptions Terminology

Categories of Exceptions

Exceptions on the OCP

Try Statement

catch里不能有try里面发生不了的checked Exception,
原理也是不能存在到达不了的Exception。

Throw vs. Throws

Creating Custom Exceptions

public class CannotSwimException extends Exception {
    public CannotSwimException() {
        super();
    }
    public CannotSwimException(Exception e) {
        super(e);
    }
    public CannotSwimException(String message) {
        super(message);
    }
}

有3种构造方法。

Using Multi-catch

try {
    throw new IOException();
} catch (FileNotFoundException | IOException e) { } // DOES NOT COMPILE

出FileNotFoundException已经包含在IOException中的错。
这个如果分开写,就跟IOException写在上面一样会出错。但是错误内容不同。

左右没有分别。

Using Try-With-Resources

Try-With-Resources Basics

AutoCloseable

和Closable接口的区别
■■ Closeable restricts the type of exception thrown to IOException.
■■ Closeable requires implementations to be idempotent.

Suppressed Exceptions

public void close() throws IllegalStateException {
    throw new IllegalStateException("Cage door does not close");
}

try (JammedTurkeyCage t = new JammedTurkeyCage()) {
    throw new RuntimeException("turkeys ran off");
} catch (IllegalStateException e) {
    System.out.println("caught: " + e.getMessage());
}
Exception in thread "main" java.lang.RuntimeException: turkeys ran off
atJammedTurkeyCage.main(JammedTurkeyCage.java:20)
Suppressed: java.lang.IllegalStateException: Cage door does not close

最后出力的内容可以看出来,
虽然IllegalStateException发生了,但被Suppress到了RuntimeException里面了。
因此没有catch到IllegalStateException这个错。

自动close的时候是按resource生成的逆序关闭。

public class JammedTurkeyCage implements AutoCloseable {

    @Override
    public void close() throws IllegalStateException {
        throw new IllegalStateException("Cage door does not close");
    }

    public static void main(String[] args) throws IOException {

        try (JammedTurkeyCage t = new JammedTurkeyCage()) {
            throw new IllegalStateException("turkeys ran off");
        } finally {
            throw new RuntimeException("and we couldn't find them");
        }
    }

}
Exception in thread "main" java.lang.RuntimeException: and we couldn't find them
    at com.apibot.JammedTurkeyCage.main(JammedTurkeyCage.java:20)

可以看出来,try里面出的错丢失了,最后finally执行的时候,会丢失掉前面的exception。
而别的用法,因为发生了suppressed exception所以不会被丢失。

Putting It Together

Rethrowing Exceptions

Working with Assertions

The assert Statement

Enabling Assertions

Using Assertions