Java 中的两种异常(Checked exceptions 和 Unchecked exceptions)

Java中定义了两种类型的异常

  1. Checked exceptions:checked exceptions继承自Exception类,调用抛出这种异常API的客户端代码必须要处理导常,否则是不能通过编译的,该异常要么被catch子句捕获要么通过throws子句继续抛出。如:SQLException
  2. 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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值