java 异常 程序终止,java异常会终止整个java应用程序吗?

这篇博客探讨了Java应用程序中异常处理的情况。作者原先认为一旦发生异常,整个应用会终止,但实际发现应用会继续执行后续代码。博主通过一个测试函数说明,即使引发FileNotFoundException,程序也不会立即终止。只有当所有非守护线程都结束或者调用System.exit()时,程序才会真正终止。这表明Java异常更像是强大的break语句,可以跳出方法,但不会强制关闭程序。
摘要由CSDN通过智能技术生成

I used to think that when an exception happened, the whole java application will be terminated. For example, I write a test function to test my idea.

public void test(){

File fileDir=new File(sourceDataDir);

if(fileDir.exists()){

File[] files = fileDir.listFiles();

for(int index=0 ; index

System.out.println("index = "+index);

File file = files[index];

if(index == 1)//delete a file to cause a FileNotFoundException

file.delete();

try {

BufferedReader in = new BufferedReader(new FileReader(file));

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

}

}

I delete a file to cause a FileNotFoundException manually. I used to think that the whole application will terminate when the exception happened. But in fact, the application will continue reading the remaining files. So, my question is, in what condition an exception will cause the whole application to be terminated?

解决方案

my question is ,in what condition ,a exception will cause the whole application to be terminated?

It won't ever. Only System.exit() causes the whole program to terminate (and a JVM crash)

Think of an Exception and like a powerful break; which can break out of methods. A break could result in a loop exiting and if the last loop in the only non daemon thread, the program will exit. But it doesn't cause it, even though it might be the last thing you see before you program dies.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值