一、类继承结构
java.lang.Object
|- java.lang.Throwable
|- java.lang.Error
|- java.lang.Exception
二、Throwable、Error和Exception的区别
Throwable
所有error/exception的父类,只有其实例可被throw & catch。
Error
应用程序不应试图捕获的严重错误
Exception
异常
三、高level代码处理低level代码中异常的推荐做法
1.
try {
lowLevelOp();
} catch (LowLevelException le) {
throw new HighLevelException(le); // Chaining-aware constructor
}
2.
try {
lowLevelOp();
} catch (LowLevelException le) {
throw (HighLevelException) new HighLevelException().initCause(le); // Legacy constructor
}
stacktrace中的“... 3 more”表示至最顶层还有3层
五、getLocalizedMessage()
Throwable的子类可以覆盖getLocalizedMessage()方法来实现多区域语言
六、checked/unchecked exception
RuntimeException和Error为unchecked exception,其余都为checked exception。
七、原则
尽早处理,不要把SQLException扔到业务层,可以考虑转换为RuntimeException
try {
// do something
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
上层也处理不了的可转换为RuntimeException
一般情况下不要catch顶层的exception(RuntimeException,Error)
不要使用异常来控制流程
exception应只打印一次
八、可复用的常见exception
IllegalArgumentException
IllegalStateException
NullPointerException
IndexOutOfBoundsException
ConcurrentModificationException
UnsupportedOperationException