Does throwing an Exception have to cause the program to terminate
Does throwing an Exception have to cause the program to terminate?
I thin开发者_Python百科k its no, I just want to make sure
It depends on the thread where the exception is thrown, and on the other threads running on the same time in the application.
An uncaught exception 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:
The Java Virtual Machine exits when the only threads running are all daemon threads.
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.
In Java and .NET, if you don't handle an exception, it will most like cause your program to terminate.
Simply throwing an exception will not terminate the program, as such. It is what happens after it was thrown that determines what will occur.
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).
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);
}
精彩评论