异常

异常

截图

捕获异常

package com.exception;

public class Test2 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        //假设要捕获多个异常:从小到大!
        //快捷键Ctrl+Alt+T 自动生成
        try{//try 监控区域
            System.out.println(a/b);
        }catch (Error e){//catch(想要捕获的异常类型!) 捕获异常
            System.out.println("Error");
        }catch (Exception e){//catch(想要捕获的异常类型!) 捕获异常
            System.out.println("Exception");
        }catch (Throwable e){//catch(想要捕获的异常类型!) 捕获异常
            System.out.println("Throwable");
        } finally {//处理善后工作
            System.out.println("finally");
        }
        //Throwable不能和Exception交换位置,然后Throwable覆盖了Exception
        //finally 可以不要finally,假设IO,资源,关闭!

    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }
}

抛出异常

package com.exception;

public class Test3 {
    public static void main(String[] args) {
        new Test3().test(1,0);
    }
    //假设方法中,处理不了这个异常,方法上抛出异常
        public void test(int a,int b) throws ArithmeticException{
            if(b==0){
                throw new ArithmeticException();//主动抛出异常,一般在方法中使用
            }
            System.out.println(a/b);
    }
}
//主动是throw
//在方法上是throws,使用这个需要在new那里使用Ctrl+Alt+T

自定义异常

package com.exception.demo02;
//自定义的异常类
public class MyException extends Exception{

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

    public MyException(int a) {
        this.detail=a;
    }
    //toString:异常的打印信息

    @Override
    public String toString() {
        return "MyException{" + detail + '}';
    }
}
package com.exception.demo02;

public class Test {
    //可能会存在异常的方法
    static void test(int a) throws MyException {
        System.out.println("传递的参数为:"+a);
        if(a>10){
            throw new MyException(a);//抛出
        }
        System.out.println("OK");
    }

    public static void main(String[] args) {
        try{
            test(11);
        }catch (MyException e){
            System.out.println("MyException=>"+e);
        }
    }
}
posted @ 2025-07-19 13:32  A那就算了吧  阅读(7)  评论(0)    收藏  举报