Java异常02:捕获和抛出异常

异常处理机制

# 抛出异常

# 捕获异常

# 异常处理五个关键字

        try,catch,finally,throw,throws

try-catch-finally

package demo01;

public class Test {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try {  // try 监控区域
            System.out.println(a / b);
        } catch (ClassCastException d) {
            // 只能捕获对应的异常类型
            System.out.println("ClassCastException");
        } catch (ArithmeticException e) {
            // catch(想要捕获的异常类型) 捕获异常,捕获对应的异常类型输出下面的语句
            System.out.println("程序出现异常,变量b不能为0");
        } catch (RuntimeException f) {
            /*
            catch 可以写多个,捕获多个异常
            捕获的异常类型一般都范围大的异常写在下面。从小到大的去捕获
            如果异常写在上面捕获了,就不会执行下面的捕获了
            要有一种层层递进的感觉,不然写个 Throwable 什么异常都能捕获
            下面也没必要再去写捕获异常了,当然这样写也会错
             */
            System.out.println("RentimeException");
        } finally {
            /*
            finally 处理善后工作,不论有没有异常都会执行,
            如:之后学习 IO 流的时候需要关闭,关闭的时候可以放到 finally 里面一
            finally 区域可以不要,try,catch 必须有
            */
            System.out.println("finally");
        }
        /*
        通过 catch 捕获异常后,可以让程序继续运行
        */
    }
}
package demo01;

public class Test2 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        /*
        System.out.println(a/b);
        快捷键,选中当前代码 Ctrl+Alt+T
         */
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            throw new RuntimeException(e);
            // 打印错误的栈信息
        } finally {
        }
    }
}

throw-throws 

package demo01;

public class Test3 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        if (b == 0) {  // 主动抛出异常  throw
            throw new ArithmeticException();
        }
        System.out.println(a/b);
    }
}
package demo01;

public class Test3 {
    public static void main(String[] args) {
        try {
            new Test3().test(1, 0);
        } catch (ArithmeticException e) {
            // 捕获下面抛出的异常
            throw new RuntimeException(e);
        } finally {
        }
    }
    public void test(int a,int b) throws ArithmeticException {
        if (b == 0) {
            // 假设这个方法中,处理不了这个异常,可以在方法上抛出异常,throws
            throw new ArithmeticException();
            // 主动抛出异常一般在方法中使用
        }
        System.out.println(a / b);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值