java try-catch-finally 代码块 不执行catch直接执行finally
文章目录
在执行java的try-catch-finally代码块的时候,不执行catch的代码块,catch捕获的是Exception,而直接执行finally,如下所示:
public static void systemerror(){
List<Object> list = new ArrayList<>();
while (true) {
list.add(new byte[1024 * 1024]); // 添加一个1MB的对象到列表中
}
}
public static void run(){
try{
System.out.println("1");
System.out.println("2");
systemerror();
System.out.println("3");
}catch(Exception e) {
System.out.println("exception "+e);
}finally{
System.out.println("finally");
}
System.out.println("end");
}
public static void main(String[] args) {
run();
}
执行1,2,然后直接到finally,原因是产生了系统级异常,该异常不能通过Exception捕获,需要通过Error捕获
public static void systemerror(){
List<Object> list = new ArrayList<>();
while (true) {
list.add(new byte[1024 * 1024]); // 添加一个1MB的对象到列表中
}
}
public static void run(){
try{
System.out.println("1");
System.out.println("2");
systemerror();
System.out.println("3");
}catch(Error e) {
System.out.println("exception "+e);
}finally{
System.out.println("finally");
}
System.out.println("end");
}
public static void main(String[] args) {
run();
}

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论