18.异常处理

image

image

image

image

image

package 异常;

import oop.demo_6.Test;

public class exception {
    public static void main(String[] args) {
        int i = 1;
        int j = 0;
    //要捕获多个异常要从小到大,Error——Throwable
        try {//try监控区域
            System.out.println(i/j);
        }catch (Error a){//报错,捕获异常
            System.out.println("Error");//小
        }catch (Exception b){
            System.out.println("Exception");//中
        }catch (Throwable c){
            System.out.println("Throwable");//大
        }
        finally {//处理善后工作
            System.out.println("善后工作");
        }

//Ctrl+alt+T 包裹  快捷键
        try {
            System.out.println(i/j);
        } catch (Exception e) {
            System.exit(1);//如果报错,程序结束,手动结束;
            e.printStackTrace();//打印错误的栈信息
        }

public class exception {
    public static void main(String[] args) {
    
        exception exception = new exception();
        try {
            exception.test(1,0);
        } catch (ArithmeticException e) {//捕获抛出的异常
            e.printStackTrace();//打印错误信息
        }

    }

    public void test(int i,int j)throws ArithmeticException{
        if (j == 0){// throw,throws 主动抛出异常
            throw new ArithmeticException();//主动抛出异常,最好在方法中使用
        }
    }

}

posted @ 2022-05-24 08:28  王小瘦的园子  阅读(20)  评论(0编辑  收藏  举报