这里考察的是 Java 异常处理机制
NoClassDefFoundError ,VirtualMachineError, OutOfMemoryError,StackOverflowError
NullPointException ,ClassCastException ,ClassNotFoundException
IOException 、SQLException
曾经开发过程中有一同学就遇到这样的问题,程序跑的好好的,并且程序进行 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"); //实例化异常
}
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有