java异常会终止整个java应用程序吗? [英] Will a java exception terminate the whole java application?

查看:1226
本文介绍了java异常会终止整个java应用程序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前认为当发生异常时,整个java应用程序将被终止。例如,我写了一个测试函数来测试我的想法。

  public void test(){
File fileDir =新的File(sourceDataDir);
if(fileDir.exists()){
File [] files = fileDir.listFiles(); (int index = 0; index< files.length; index ++){
System.out.println(index =+ index);

文件文件= files [index];
if(index == 1)//删除文件导致FileNotFoundException
file.delete();
try {
BufferedReader in = new BufferedReader(new FileReader(file));
} catch(FileNotFoundException e){
e.printStackTrace();
}
}
}
}

删除文件以手动导致 FileNotFoundException 。我以前认为整个应用程序将在异常发生时终止。但事实上,应用程序将继续读取剩余的文件。所以,我的问题是,在什么情况下,异常会导致整个应用程序被终止?

解决方案


我的问题是,在什么情况下,异常会导致整个应用程序被终止?


永远不会。只有System.exit()导致整个程序终止(并且JVM崩溃)



想想一个例外,就像一个强大的 break; / code>可以突破方法。中断可能导致循环退出,如果唯一的非守护线程中的最后一个循环,程序将退出。但是它不会导致它,尽管它可能是您在程序死亡之前看到的最后一件事。


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<files.length ; 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.

这篇关于java异常会终止整个java应用程序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆