捕获和抛出异常

本文介绍了Java异常处理的五个核心关键字:try、catch、finally、throw和throws。通过示例代码展示了如何使用这些关键字来捕获、处理和抛出异常,强调了finally块在资源释放中的重要性。同时,解释了如何在方法上使用throws声明异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常处理五个关键字

try、catch、finally、throw、throws

package 异常;

public class Demo01 {
    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("程序出现异常");
        }catch (Error e){
            System.out.println("Error");
        }
        catch (Exception e){
            System.out.println("Exception");
        }
        catch (Throwable e){
            System.out.println("Throwable");
        } //可以捕获多个异常,但是级别需要从小到大
        finally { //finally处理善后工作,finally一些情况下可以不要,但try..catch需要
            System.out.println("finally");
        }

        //快捷键 ctrl+alt+T可以自动生成相应的代码块

    }
}
输出结果:
程序出现异常
finally

主动抛出异常

throw

package 异常;

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

        try {
            if(b==0){ //明确知道某种情况下会出错的话,可以使用throw主动抛出异常
                throw new ArithmeticException();
            }
            System.out.println(a/b);
        }
        catch (Exception e){
            System.out.println("Exception");
        }
    }
}

throws

package 异常;

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

        new Demo01().test(a,b);
    }
        public void test(int x,int y) throws ArithmeticException{//假设这个方法解决不了异常,可以在方法上抛出异常
        if(y==0){
            throw new ArithmeticException();
        }
        System.out.println(x/y);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值