Java 中的两种异常(Checked exceptions 和 Unchecked exceptions)
Java中定义了两种类型的异常
- Checked exceptions:checked exceptions继承自Exception类,调用抛出这种异常API的客户端代码必须要处理导常,否则是不能通过编译的,该异常要么被catch子句捕获要么通过throws子句继续抛出。如:SQLException
- Unchecked exceptions:RuntimeException也是继承自Exception类,然而所有继承自RuntimeException的异常被特殊对待,没有要求客户端调用时必须处理这种类型异常。如:NullPointerException、ArrayIndexOutOfBoundException
Checked exceptions
ExceptionTester类
package cn.sehzh;
public class ExceptionTester {
public void testException() throws Exception {
throw new Exception("异常");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Main类
package cn.sehzh;
public class Main {
public static void main(String[] args) {
ExceptionTester exceptionTester = new ExceptionTester();
try {
//客户端调用时必须捕获或抛出,这里采用捕获
exceptionTester.testException();
} catch (Exception e) {
e.printStackTrace();
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
Unchecked exceptions
ExceptionTester类
package cn.sehzh;
public class ExceptionTester {
public void testException(){
throw new RuntimeException("运行时异常");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Main类
package cn.sehzh;
public class Main {
public static void main(String[] args) {
ExceptionTester exceptionTester = new ExceptionTester();
//这里没有要求客户端调用时必须处理
exceptionTester.testException();
}
}