11.2

异常

  • 所有异常类都继承Throwable有两个子类,Error 和 Exception
  • 使用try catch 和 try catch finally
  • catch块必须子类在前父类在后。
public class TryCatchTest {

    public static void main(String[] args) {
        TryCatchTest te = new TryCatchTest();
        int result = te.test();
        System.out.println(result);
    }
    /**
     * divider(除数):
     * result(结果):
     * 给定一个除数,每次循环除数减一,result = result + 100/divider。
     * 如果捕获异常,打印输出“捕获异常了!!!”
     * finally打印输出“这是finally!!!”
     * 最后返回result = 999。
     * @return
     */
    public int test() {
        int divider = 10;
        int result1 = 0;

        try {
            while (divider > -1) {
                result1 = result1 + 100/divider; 
                divider--;
            }
        } catch (Exception e) {
            System.out.println("捕获异常了!!!");
        }finally {
            System.out.println("这是finally!!!");
        }
        return 999; 
    }   
}
  • 方法用throws关键字声明有异常,方法中throw该异常,调用者用try catch捕获,或者继续声明异常,给更上一层的调用者。
异常连:
public class ChainTest {

    public static void main(String[] args) {
        ChainTest test = new ChainTest();
        try {
            test.test2();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/**
 * test1抛出DrunkException异常。
 * test2调用test1,捕获DrunkException异常,包装成RuntimeException。
 * @throws DrunkException
 */
    public void test1() throws DrunkException {
        throw new DrunkException("喝大了!!");  
    }

    public void test2(){
        try {
            test1();
        } catch (DrunkException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值