Java异常类

异常处理

Error和Exception

  1. 检查性异常:用户错误引起,程序员无法预见,例如打开不存在的文件。
  2. 运行时异常:可在编译时忽略
  3. 错误:不是程序员造成,可能是栈溢出,由Java虚拟机生成并抛出,JVM一般会选择终止线程。

异常处理框架

RuntimeException//运行时异常
ArrayIndexOutOfBoundsException//数组下标越界
NullPointerException//空指针异常
ArithmeticException//算术异常
MissingResourceException//丢失资源
ClassNotFoundException//找不到类
    
StackOverFlowError

捕获和抛出异常

try、catch、finally、throw、throws

public class Test {   
    public static void main(String[] args) {
        int a = 1;
        int b = 0;
        try{ //try监控区域                                   
            System.out.println(a/b);
        //假设要捕获多个异常,要从小到大捕获
        }catch(ArithmeticException e){ //想要捕获的异常类型
            System.out.println("程序出现异常,变量b不能为0");
        }finally { //处理善后工作,可以不要
            System.out.println("finally");
        }
    }
    public void test(int a, int b) {
        
    }
}
//Ctrl + Alt + T
public class Test {   
    public static void main(String[] args) {
       new Test().test(1,0);
    }
    //假设这方法中,处理不了这个异常,方法上抛出异常
    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(1);
        }catch(MyException e) {  //e是toString方法
            System.out.println("MyException=>" + e);
        }
    }
    
}
posted @ 2021-03-05 09:41  Barrymeng  阅读(65)  评论(0)    收藏  举报