java 抛出异常是否必须导致程序终止
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4493832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does throwing an Exception have to cause the program to terminate
提问by Stephanie Dente
Does throwing an Exception have to cause the program to terminate?
抛出异常是否必须导致程序终止?
I think its no, I just want to make sure
我认为不是,我只是想确定一下
回答by Eyal Schneider
It depends on the thread where the exception is thrown, and on the other threads running on the same time in the application.
这取决于抛出异常的线程,以及应用程序中同时运行的其他线程。
An uncaughtexception terminates the thread where it was thrown. If the rest of the threads are only daemon threads, then yes, the application will be terminated.
一个未捕获的异常终止的地方抛出的线程。如果其余线程只是守护线程,那么是的,应用程序将被终止。
According to Thread.setDaemon(boolean)documentation:
根据Thread.setDaemon(boolean)文档:
The Java Virtual Machine exits when the only threads running are all daemon threads.
当唯一运行的线程都是守护线程时,Java 虚拟机退出。
回答by Oded
In Java and .NET, if you don't handle an exception, it will most like cause your program to terminate.
在 Java 和 .NET 中,如果您不处理异常,它很可能会导致您的程序终止。
Simply throwing an exception will not terminate the program, as such. It is what happens after it was thrown that determines what will occur.
因此,简单地抛出异常不会终止程序。抛出之后发生的事情决定了会发生什么。
回答by Sodium Hydroxide
No, it does not have to cause it to terminate. You could catch the exception and do something useful with it, like show a message to the user that an error occurred and why.
不,它不必导致它终止。您可以捕获异常并使用它做一些有用的事情,例如向用户显示发生错误以及原因的消息。
回答by David
Failing to catch an exception will likely cause the program to terminate, but the act of throwing one will not. At the very least, any application should have some kind of last line of defense for catching all otherwise unhandled exceptions and handling them (even if handling them means, for some at least, throwing them outside of the application and terminating because something external to the application expects this).
未能捕获异常可能会导致程序终止,但抛出异常的行为不会。至少,任何应用程序都应该有某种最后一道防线来捕获所有其他未处理的异常并处理它们(即使处理它们意味着,至少对某些人来说,将它们扔到应用程序之外并由于某些外部的东西而终止)应用程序期望这一点)。
回答by EnabrenTane
Only "Unhandled Exceptions" will cause your program to crash. To handle exceptions you use the following form
只有“未处理的异常”会导致您的程序崩溃。要处理异常,请使用以下形式
try {
// May Throw ApocalypseException
functionThatMightBlowUpTheWorld();
}
catch (ApocalypseException e){
System.err.println("We accidentally almost blew up the world because: ");
System.err.println(e.message);
}