I'm currently working on a project that logs data from a website to a database every x hours.
But when the database connection properties are not good, the program does not throw a RuntimeException
pretends everything is fine.
private static ScheduledExecutorService executeWithPeriod(Runnable runnable, int period) {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.schedule(runnable, Math.max(1, period), TimeUnit.HOURS);
return executor;
}
The runnable
takes care of getting data and saving it to the database.
RuntimeException
: All these exceptions extends RuntimeException
Someone have the solution to throws the RuntimeException
to the main thread?
Well, since the task is just to tnrow a RuntimeException, how about this?
class MyRunnable implements Runnable {
public void run() {
throw new RuntimeException("mark my words");
}
}
Rest assured this code throws an exception. You can try using this code:
public static void main(String[] args) {
new MyRunnable().run();
}
However usually Runnables are run in their own thread:
new Thread(new MyRunnable()).start()
So now the exception is thrown as well. However it terminates the thread - and that's it.
I am coming back to my question from the comment: What are you trying to achieve?
You haven't demonstrated a need for multiple threads, so you can eliminate the complexity of signaling between concurrent threads. Use a single thread instead:
final class YourTask {
public static void main(String... args) throws InterruptedException {
YourTask task = new YourTask();
while (true) {
try {
task.doYourThing();
} catch (Exception ex) {
ex.printStackTrace();
break;
}
TimeUnit.HOURS.sleep(1L);
}
}
private void doYourThing() throws Exception {
System.out.println("I'm saving data from a website to a database!");
throw new RuntimeException("Oh no! I can't read my configuration!");
}
}
Note that this solution "tells the user about the problem" and "stops the whole program," as specified.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.