萌新学Java之 Exception 异常

RuntimeException(运行时异常):

ArrayIndexOutOfBoundsException(数组下标越界)

NullPointerException(空指针异常)

ArithmeticException(算术异常)

MissingResourceException(丢失资源)

ClassNotFoundException(找不到类)

可以看到报了算术异常 ArithmeticException,所以需要捕获异常

try 代码块里放需要执行的操作

catch 代码块里放出现异常后的措施

finally 代码块不管报不报异常都执行

try {

        // try 监控区域

} catch (异常名 e) {

        // catch 捕获异常

} finally {

        //处理善后工作

}

public class Try {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        try { //try监控区域
            System.out.println(a / b);
        }catch (ArithmeticException e){ //catch捕获异常
            System.out.println("执行异常,被除数不能为0");
        }finally { //处理善后工作
            System.out.println("finally");
        }

    }

}

运行结果:

快捷键:ctrl + alt + t

选择 try / catch / finally 也能直接生成捕获异常代码块

抛出异常:throw、throws(写的位置不一样)

主动抛出的异常,一般在方法中使用

throws 主要在方法上抛出异常

public class Try {
    public static void main(String[] args) {
        try {
            new Try().test(1,0);
        } catch (ArithmeticException e) {
            throw new RuntimeException(e);
        }
    }

    //假设这个方法中,处理不了这个异常,方法上抛出异常
    public void test(int a,int b) throws ArithmeticException{
        if(b == 0){
            throw new ArithmeticException(); //主动抛出的异常,一般在方法中使用
        }
    }

}

注意自定义的方法不要写在 main 方法里

自定义异常,在类后面加 extends Exception

在多重 catch 块后面,可以加一个 catch(Exception) 来处理可能会被遗漏的异常

对于不确定的代码,也可以加上 try-catch,处理潜在的异常

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值