异常、断言和日志

异常、断言和日志

处理错误

异常分类

Java中的异常层次结构
classDiagram
    Throwable <|-- Error
    Throwable <|-- Exception
    Exception <|-- IOException
    Exception <|-- RuntimeException
    class Error
    class Exception
    class IOException
    class RuntimeException

创建异常类

1
2
3
4
5
6
class FileFormatException extends IOException {
public FileFormatException() {}
public FileFormatException(String gripe) {
super(gripe)
}
}

捕获异常

捕获多个异常

1
2
3
4
5
6
7
try {

} catch (FileNotFoundException | UnknownHostException e) {

} catch (IOException e) {

}

再次抛出异常与异常链

1
2
3
4
5
6
7
try {

} catch (SQLException e) {
Throwable se = new ServletException("datebase error");
se.initCause(e);
throw se;
}

带资源的try语句

1
2
3
try (Resource res = ...) {

}

在try块退出时,会自动调用res.close方法。还可以自定义实现AutoCloseable接口的类,来实现带资源的try语句,资源的关闭顺序是倒序的


异常、断言和日志
http://xrcol.github.io/2023/03/19/69efd1704bf5/
作者
XR
发布于
2023年3月19日
许可协议