Why does the program not terminate when a method that throws RuntimeException is called without handling the exception in Java?
The program you have posted will terminate when you throw the uncaught exception. I just tested it myself.
The only way to prevent the JVM from terminating is to have non-daemon threads running. If you have displayed a GUI for instance, you must make sure you terminate the EDT to for the application to terminate completely.
Runtime exception not terminating the programm
A RuntimeException
(or any Exception
or Throwable
) does not necessarily terminate your application.
It only terminates your applications if it's thrown on the only non-daemon thread and is not handled.
That means that if either another non-daemon thread is running or you catch the exception, the application will not be terminated.
This recent answer from me gives a summary of what happens (it's specifically about an OutOfMemoryError
, but the idea is the same).
Java exception: why my program is not terminating?
But this code, also printing the line after Occurrence of error
Because it is out side of try-catch, that is the advantage of exception handling.
Exception handling prevents the abnormal termination of program due to run time error. And that is what happened.
See also
- exception handing docs
Throw exception and NOT terminate program in java
I figured out what and how to do what I was needing. What I needed to stop the creation of the routine object if conditions were met, and that was done by throwing an error. That was being done, but I was mistakenly setting the variables INSIDE the try...catch
block. So, if the conditions are not satisfied, it fails and stops, if they are satisfied, it creates the object and sets the variables OUTSIDE of the try...catch
block, which works. My new code is as follows:
package routines;
import java.io.IOException;
import java.util.Random;
import game.*;
public class MovePlayer extends Routine {
private final int destX;
private final int destY;
private final Random random = new Random();
public MovePlayer(int destX, int destY, GameBoard board) throws IOException {
super();
try {
if (destY > board.getHeight() || destX > board.getWidth()) {
throw new IllegalArgumentException(">>> Error while creating routine, one or more coords are outside of the game board");
} else {
}
} catch (IllegalArgumentException e) {
fail();
System.err.println(e.getLocalizedMessage());
}
this.destX = destX;
this.destY = destY;
}
Does Exception Terminate Program?
Is re-throwing by throw new RuntimeException causing the program to stop?
Yes, because as per the documentation there is no matching catch. In order to continue execution you would need to catch
the second exception (RuntimeException
) by using a nested try/catch
which is generally not a great idea:
try {
// something with PDO that generates an exception
} catch (PDOException $e) {
// do some stuff
try {
throw new RuntimeException();
} catch (RuntimeException()) {
// do something else
}
}
In other words, would the catch & fwrite statement sufficiently 'catch' the exception and allow the program to continue?
If you want to continue with the program then you would need to not throw the second exception. However, anything that happened before you throw that exception will occur. So in your example the fwrite
would still happen, the program would just be halted when the RuntimeException
is encountered.
Does an unhandled runtime exception crash the whole server?
Will an unhandled runtime exception stop the whole server (i.e. Spring Boot application) or just the specific HTTP request ?
There is usually a thread pool
in web server to handle all requests(e.g tomcat
). Uncaught exceptions that occur in your controller
will eventually be caught somewhere, so it will not cause the worker thread
in the thread pool
to be killed.
Tomcat#AbstractEndpoint#processSocket:
Executor executor = getExecutor();
if (dispatch && executor != null) {
// handle request in thread poll
executor.execute(sc);
}
I did a simple debug. Assuming that an unhandle exception
occurred in your controller
, then the exception was actually caught by FrameworkServlet#processRequest
. After the capture, it will be wrapped into a NestedServletException
and continue to be thrown to the upper layer. Eventually, it will be caught and printed in StandardWrapperValve#invoke
.
What's the best way to terminate a program on error?
If you want it to be clean (i.e. not display stacktrace to user), then throwing exceptions is out of the question (at least out of main). Then it's all about whether you want to return an exit code from the program if not.
If you want to return the exit code, you have to use System.exit(int errcode);
. Otherwise you can just return (or let main
exit normally).
Why does this exception not cause a runtime error?
when the
NullPointerException
is thrown, why does it not terminate the thread as I expected?
Because the thread is not going to terminate unless the exception travels all the way up the invocation chain.
I thought as there was not a try catch block in the same method, it would cause an exception and halt the program.
It's not the same method, it's in any of the methods up the chain of invocation - in this case, main
catches the exception, preventing the thread from terminating.
Related Topics
How to Use Comparator to Define a Custom Sort Order
Is the Order of Values Retrieved from a Hashmap the Insertion Order
Java Says Filenotfoundexception But File Exists
Get Battery Level and State in Android
How to Add a Textview to Linearlayout in Android
Recyclerview Horizontal Scrolling to Left
How to Avoid Installing "Unlimited Strength" Jce Policy Files When Deploying an Application
Java: How to Get Input from System.Console()
Platform.Runlater and Task in Javafx
How to Parse JSON Array with Gson
Format Float to N Decimal Places
Finish All Previous Activities
Find Oracle Jdbc Driver in Maven Repository
Java Error When Trying to Run Netlogo Headlessly on a Cluster
Cmake Can't Find Java, But It's Installed
Remote Debugging a Java Application
What Determines the Current Working Directory of Tomcat Java Process