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("异常");
- }
- }
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();
- }
- }
- }
- Unchecked exceptions
ExceptionTester 类
- package cn.sehzh;
- public class ExceptionTester {
- public void testException(){
- throw new RuntimeException("运行时异常");
- }
- }
Main 类
- package cn.sehzh;
- public class Main {
- public static void main(String[] args) {
- ExceptionTester exceptionTester = new ExceptionTester();
- // 这里没有要求客户端调用时必须处理
- exceptionTester.testException();
- }
- }
来源: http://www.bubuko.com/infodetail-2631947.html