JAVASE学习 异常

本文详细介绍了Java异常处理的概念,包括异常体系结构,错误与异常的区别,如何使用try-catch-finally捕获和处理异常,以及如何通过throw关键字主动抛出异常。此外,还展示了如何自定义异常,并给出了实际应用中的经验总结,强调了异常处理在程序健壮性中的重要性。
摘要由CSDN通过智能技术生成

0x00

本章的大致简介

                                                                                                                                                                        

0x01 什么是异常

 

异常体系结构

所有的异常都是Throwable的子类

错误和异常不同,错误更加致命

Error

不在我们的应用程序之内,是java虚拟机内的错误

错误是致命性的错误,是程序无法控制和处理的

Exception

非运行时异常

所以异常是一定要处理的

0x02 捕获和抛出异常

通过try,catch,finally来捕获

package exceptionStudy;

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){//捕获异常
            System.out.println("程序出现异常,b不能为0");
        }finally {//处理善后工作
            System.out.println("finally");
        }
    }
}

finally可以不要,但是可以用finally来关闭资源

 

捕获多个异常

package exceptionStudy;

public class Demo01 {
    public static void main(String[] args) {
        //如果要捕获多个异常,从小到大写
        try {//try 监控区域
            new Demo01().a();//调用a方法
        }catch (Error e){//catch里的参数:想要捕获的异常类型
            System.out.println("程序出现异常,b不能为0");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        }finally {//处理善后工作
            System.out.println("finally");
        }
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
}

生成代码块的快捷键

package exceptionStudy;

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

        //快捷键:ctrl alt t
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            e.printStackTrace();//打印错误的栈信息
        } finally {
        }
    }
}

Throw关键字

在方法中主动抛出异常

package exceptionStudy;

public class Demo01 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        new Demo01().test(a,b);
    }
    
    //假设在方法中,处理不了这个异常,方法上抛出异常,抛到下一级
    public void test(int a ,int b) throws ArithmeticException{
        if(b==0){
            throw new ArithmeticException();//一般在方法钟主动抛出异常
        }
    }
}

0x03 自定义异常

package exceptionStudy;

//继承异常类,自定义异常
public class MyException extends Exception{

    //传递数字>10
    private int detail;

    public MyException(int a){
        this.detail = a;
    }

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

0x04 实际运用中的经验总结

至此javase过了一遍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值