flora222

Java异常

Java异常


2026.01.16

什么是异常


软件程序在运行过程中,可能会遇到一些异常问题,比如用户输入不符合程序的要求,程序要

打开的文件不存在等等

我们把这些情况称为异常,英文Exception

异常分为三类:

检查性异常:用户错误或问题引起的异常,是无法预见的

运行时异常:有可能被程序员避免,可以在编译时被忽略,

错误ERROR:错误不算异常,是脱离程序员控制的问题,在代码中通常被忽略

​ 比如,当栈溢出时,一个错误就发生了,编译也检查不到

我们亲爱的Java也是什么都当对象啊,把异常当做对象来处理,定义了一个类

java.lang.Throwable作为所有异常的超类

JavaAPI中已经定义了许多异常类,分为ERROR(无法预见)和异常(基本可预见)两大类

捕获与抛出异常


package com.flora.base.Exception;
//假设需要捕获多个异常,我们一定要从小到大的捕获
public class Demo01 {
    static void main(String[] args) {
        int a=1;
        int b=0;
        try{//try监控区域
            System.out.println(a/b);
        }catch(Exception r){//catch(想要捕获的异常类型)捕获异常
            System.out.println("你这杂鱼!运行不了啦!b!=0");
        }catch(Throwable throwable){
            System.out.println("Throwable");
        } finally{//finally善后工作
            System.out.println("finally");
        }
        //运行结果:
        //你这杂鱼!运行不了啦!b!=0
        //finally

        //finally可以不使用
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
}
package com.flora.base.Exception;
public class Demo01 {
    static void main(String[] args) {
        new Demo01().test(1,0);
    }
    //假设方法中处理不了这个异常,那就在方法上抛出异常,关键字throws
        public void test ( int a, int b)throws ArithmeticException{
            if (b == 0) {//主动抛出异常,关键字throw一般在方法中使用
                throw new ArithmeticException();
            }
        }
    }
//运行结果:
//Exception in thread "main" java.lang.ArithmeticException
//at com.flora.base.Exception.Demo01.test(Demo01.java:9)
//at com.flora.base.Exception.Demo01.main(Demo01.java:5)


package com.flora.base.Exception;

public class Test02 {
    static void main(String[] args) {
        int a=1;
        int b=0;
        //选中对应代码,快捷键ctrl+alt+t自动包裹
        try {
            System.out.println(a/b);
        } catch (Exception e) {
            throw new RuntimeException(e);//抛出错误的栈信息
        } finally {
        }
    }
}

自定义异常


//自定义异常
package com.flora.base.Exception.Demo03;
//当类继承Exception类时,这个类就是自定义异常
public class MyException extends Exception{
    //detail小于十
    private int detail;
    public MyException(int a){
        this.detail=a;
    }
    //toString:异常的打印信息
    @Override
    public String toString() {
        return "MyException{" +
                "detail=" + detail +
                '}';
    }
}

//测试
package com.flora.base.Exception.Demo03;

public class testt {
    //先写一个可能会存在异常的方法
    static void test(int a) throws MyException{

        System.out.println("传递的参数是"+a);
        if(a>=10){
            throw new MyException(a);//抛出
        }
        System.out.println("输出正常");
    }

    static void main(String[] args) {
        try {
            test(11);
        } catch (MyException e) {
            //可以在这里加一些处理异常的代码块,将损失降低
            System.out.println("Myexception==>"+e);
        }
    }
}
//输出结果:
//传递的参数是11
//Myexception==>MyException{detail=11}

异常总结


image-20260117012120208

posted on 2026-01-17 01:22  Flora2  阅读(4)  评论(1)    收藏  举报

导航