Java学习笔记(5)

1. 异常体系

在这里插入图片描述
Java 把异常当对象来处理

异常类的基类为:Trowable

随后分为两大类:Error(错误)和 Exception(异常)
在这里插入图片描述
在这里插入图片描述
我们处理的是 Exception

2. 异常处理

try,catch,finally,throw,throws

package com.xiongyi.test4;

public class exception {

    public static void main(String[] args) {

        int a = 4;
        int b = 0;

        try{
            System.out.println(a/b);
        } catch (ArithmeticException e) {
            System.out.println("抛出 1 " + e);
        } catch (Throwable e){	// 可以兜住所有异常
            System.out.println("抛出 2 " + e);
        }finally {
            System.out.println("这是finally");
        }
    }
    
}

与 Python 处理方式相似

Idea 中有包裹快捷键:Ctrl + Alt + T
在这里插入图片描述

自定义异常

继承自 Exception

package com.xiongyi.test4;

public class MyExceotion extends Exception{

    private int detail;

    public MyExceotion(int detail) {
        this.detail = detail;
    }

    // toString:异常的打印信息
    @Override
    public String toString() {
        return "MyExceotion{" +
                "detail=" + detail +
                '}';
    }
}

调用自定义异常

package com.xiongyi.test4;

public class test {

    static void testMethods(int a) throws MyExceotion {

        if (a >= 10) {
            throw new MyExceotion(a);
        }

        System.out.println("OK!");
    }

    public static void main(String[] args) {
        try {
            test.testMethods(10);
        } catch (MyExceotion myExceotion) {
            System.out.println("异常");
            myExceotion.printStackTrace();  // 打印栈信息
        }

    }

}

注意printStackTrace(),继承自Exception,用于打印栈信息

与 Python 不同,Java 的异常需要一层层的上抛(throw,throws)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值