十、Java异常

异常

Exception:运行时异常,一般由程序逻辑错误引起的 一般可以被程序处理

Error :虚拟机运行错误 Java虚拟机(JVM)一般会选择线程终止 致命性的错误

关键词:

try

catch

finally

throw

throws

package com.exception;

public class Demo1 {
    public static void main(String[] args) {
        int a=1;
        int b=0;
        //假设捕获多个异常,由小到大排列
        try {//try监控区域
            System.out.println(a/b);
        }catch (ArithmeticException e) {//catch 捕获异常
            System.out.println("程序出现异常,变量b不能为0");
        }finally {//处理善后工作 可以不要,假设IO,资源,关闭操作放finally
            System.out.println("finally");
        }
    }

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

    }
}
posted @ 2021-08-11 17:17  盐汽水mua  阅读(29)  评论(0)    收藏  举报