这里考察的是 Java 异常处理机制

  • Error 类通常指的是 Java 运行时系统内部错误或者资源耗尽错误。应用程序不会抛出该类对象,如果出现这样的错误,除了告知用户,剩下的就是尽量使得程序安全的终止。

  • 常见的 Error 有:

     

    •  
    NoClassDefFoundError ,VirtualMachineError, OutOfMemoryError,StackOverflowError
  • Exception 又有两个分支,一个是运行时异常, RuntimeException ,一个是 CheckedException 。

  • RuntimeException指的是

     

    •  
    NullPointException ,ClassCastException ,ClassNotFoundException

 

  • RuntimeException 一定是程序的错误。

  • CheckedException 

    指的是 I/O 错误导致的

     

    •  
    IOException 、SQLException

    checkedException 一般是外部错误,这个异常发生在编译阶段。Java 编译器会强制去捕获此类异常。一般会要求把这段可能出现的异常程序进行 try catch。

 

Exception和Error 有什么区别_https://mp.weixin.qq

曾经开发过程中有一同学就遇到这样的问题,程序跑的好好的,并且程序进行 try catch 了,但是程序再往下执行时就出错。但是一直在想,都Catch 住了啊,为啥没看到报错日志呢,是不是程序没有运行,后来才发现其实这个就是忘记了 Error 这个出异常了,但是没有Catch。

 

简单的说是 Error 和 Exception 都继承了 Throwable

Error 是程序无法处理的错误,出现这个错误,只能终止程序或者修改代码。Exception 是程序可以处理的异常,捕获后可恢复。

 

import java.util.ArrayList;
import java.util.List;

public class TestError {

    public static void main(String args[]){

        List<User> users = new ArrayList<User>(2); // 为啥两次就是为了打出NoClassDefFoundError

        for(int i=0; i<2; i++){
            try{
                users.add(new User(String.valueOf(0))); //will throw NoClassDefFoundError
            }catch(Error e){
                System.out.println("Catch Error "+e);
            }catch(Exception t){
                System.out.println("Catch Exception");
                t.printStackTrace();
            }
        }

        try{
            divsion(1,0);
        }catch(Error e){
            System.out.println("Catch Error "+e);
        }catch(Exception t){
            System.out.println("Catch Exception"+t);
//            t.printStackTrace();
        }
    }

    public static int divsion(int i, int j) throws Exception {
        int k = i / j;
        return k;
    }
}

class User{
    private static String USER_ID =  getUserId();

    public User(String id){
        this.USER_ID = id;
    }
    private static String getUserId() {
        throw new RuntimeException("UserId Not found"); //实例化异常
    }
}