异常处理

异常处理

五个关键字

try、catch、finall、thorow、throws

public class Main {
    public static void main(String[] args) {
        int a=1 ;
        int b=0;
        
//        Throwable>Exception=Error;要捕获多个异常,需要从小到大捕获
        try{
//            System.out.println(a/b);
            new Main().a();
        }catch(Error e){//catch(想要捕获的异常类型) 捕获异常
            System.out.println("Error");
        }catch(Exception e){
            System.out.println("Exception");
        }catch(Throwable t){
            System.out.println("Throwable");
        }

        finally {//处理善后工作,无论是否异常都会执行
            System.out.println("finally");
        }
        //finally 可以省略

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

捕获异常快捷键:

Ctrl+Alt+T选择try catch finally

主动抛出异常

public class Main {
    public static void main(String[] args)
    {
        try {
            new Main().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }

    //假设这个方法中处理不了这个异常,可以主动抛出
    public void test(int a,int b) throws ArithmeticException
    {
        if(b==0){
            throw new ArithmeticException();//主动抛出异常,一般在方法中使用
        }
        System.out.println(a/b);
    }
}

自定义抛出异常类

public class MyException extends Exception
{
    private int detail;

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

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

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(19);
        } catch (MyException e) {//e就为 toString打印出的消息
            System.out.println("MyException=>"+e);
        }
    }
}

posted @ 2023-07-01 08:58  晚枫zz  阅读(10)  评论(0)    收藏  举报