Java异常02(捕获和抛出异常)

异常处理机制
1.抛出异常
2.捕获异常

异常处理五个关键字
try、catch、finally、throw、throws

代码示例:

package com.exception;

public class Test {
    public static void main(String[] args) {
        int a=10;
        int b=0;
        try{//监控区域
            System.out.println(a/b);
        }catch(ArithmeticException e){//捕获异常 catch(想要捕获的异常类型)
            System.out.println("程序出现异常,变量b不能为0");
        }finally{//善后处理工作
            System.out.println("finally");
        }
    }

}

输出示例
在这里插入图片描述
代码示例

package com.exception;

public class Test {
    public static void main(String[] args) {
        try{//监控区域
            new Test().a();
        }catch(Error e){//捕获异常 catch(想要捕获的异常类型)
            System.out.println("程序出现异常,栈溢出");
        }finally{//善后处理工作
            System.out.println("finally");
        }
    }
    public void a(){
        b();
    }
    public void b(){
        a();
    }


}

输出示例
在这里插入图片描述
如果要捕获多个异常,异常从小到大

快捷键:control+alt+T
在这里插入图片描述

主动抛出异常一般用在方法中

代码示例:

package com.exception;


public class Test {
    public static void main(String[] args) {
        new Test().test(1,0);
    }
    public void test(int a,int b){
        if(b==0){
            throw new ArithmeticException();
        }
    }
}

输出示例
在这里插入图片描述
假设这个方法中,处理不了这个异常,向上抛出异常(throws)代码示例:

package com.exception;


public class Test {
    public static void main(String[] args) {
        try {
            new Test().test(1,0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }
    }
    public void test(int a,int b)throws ArithmeticException{
        if(b==0){
            throw new ArithmeticException();
        }
    }
}

输出示例:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_51224492/article/details/114264542