异常处理Exception

1,抛出异常
①,方法中异常的抛出与捕获

//在主函数中
        try{  new A().test(1,0);}
        catch (ArithmeticException e){
            e.printStackTrace();
        }
        
//假设这个方法中,处理不了这个异常,方法就主动抛出异常
    //方法中抛出异常然后在主函数中捕获异常就可以保证程序正常运行
    public void test(int a ,int b) throws ArithmeticException{
     if(b==0){
    throw new ArithmeticException(); //主动抛出异常 一般在方法中使用
}

②,程序执行时可能会碰到的异常,直接抛出

if(b==0){
    throw new ArithmeticException(); //主动抛出异常 一般在方法中使用
}

2,捕获异常
>VirtulMachineError
顺序 Throwable>Error>AWTError
>Exception>IOExeception
>RUNtimeException

 //Ctrl+Alt+T 可以快捷生成异常捕获机制
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace();//打印捕获的栈信息
        } finally {
        }
 //假设要捕获多个异常就顺序需要从小到大
        try{
            new demo01().a();
        }catch (Error e){
            System.out.println("被除数不能为零");
        }catch ( Exception e){
            System.out.println("Exception");
        }
        catch (Throwable e){
            System.out.println("Throwable");
        }
        //finally可以不要
        finally {
            System.out.println("finally");
        }

3,自定义异常
为了实现一些不是异常但有条件限制的操作

//定义一个变量接收值>10报异常
    private int detail;
    //构造器
    public MyException(int a){
        this.detail=a;
    }

    //toString :异常的打印信息
    @Override
    public String toString() {
        return "MyException{"+detail +'}';
    }
-------------------------
public class Test {
    //可能会存在异常的方法
    static void test(int a){
        System.out.println("传递的参数为"+a);
        if(a>10){
            try {
                throw new MyException(a);
            } catch (MyException e) {
                e.printStackTrace();
            }
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
        test(11);
    }

4,异常总结
1,在多重异常可以在最后加一个catch(Exception)来处理可能遗漏的异常
2,尽量去处理异常,切忌简单的调用printStackTrace()去打印输出
3,尽量添加finally 语句块去释放一些占用的资源

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

祈愿lucky

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值