┌───────────┐
│ Object │
└───────────┘
▲
│
┌───────────┐
│ Throwable │
└───────────┘
▲
┌─────────┴─────────┐
│ │
┌───────────┐ ┌───────────┐
│ Error │ │ Exception │
└───────────┘ └───────────┘
▲ ▲
┌─────┘ ┌──-──-┴──────────┐
│ │ │
┌─────────────────┐ ┌─────────────────┐┌───────────┐
│OutOfMemoryError │... │RuntimeException ││IOException│...
└─────────────────┘ └─────────────────┘└───────────┘
异常处理
- 方法声明可能会抛出必检异常(说明当使用该方法需要异常处理)
public void methodname throws Exception1,Exception2,..,ExceptionN { }
public void methodname throws Exception { }
- 当方法内出现必检异常且该方法不想或不能处理时用throw语句抛出
- 免检异常由JVM抛出,可以不用throw语句抛出
- 且程序会在throw语句或JVM抛出异常后立即终止
public class TestException throws Type {
public static void main(String[] args) {
int a =30;
if(a<0){
throw new Type;
}
public static void main(String[] args) {
try {
} catch (Type1 id1){
} catch (Type2 id2){
}finally {
}
}
- 如果抛出的异常对象没有try-catch 语句处理的话,则由JVM处理
- 如果抛出的异常对象是catch子句的异常类或者其子类的实例,则执行该catch块中的代码
- 将捕获底层异常类的catch子句放在前面,同时将捕获相对高层的异常类的catch子句放在后面,否则,捕获底层异常类的catch子句将可能会被屏蔽
- try 块后面接零个或多个catch块,如果没有catch块,则必须跟一个finally块