Scheduled Exception Suppresses Later Runs

An uncaught exception in a periodic task silently cancels it; wrapping the body in try/catch keeps the schedule alive after individual failures.

JavaResilience

Code

snippet
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class SchedulerExceptionSuppressor {

    public static void main(String[] args) throws Exception {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        AtomicInteger bareRuns = new AtomicInteger();
        AtomicInteger guardedRuns = new AtomicInteger();

        // an uncaught exception suppresses later runs: the task is cancelled silently
        scheduler.scheduleAtFixedRate(() -> {
            bareRuns.incrementAndGet();
            throw new IllegalStateException("boom on run " + bareRuns.get());
        }, 0, 50, TimeUnit.MILLISECONDS);

        // catching inside the task keeps the schedule alive after individual failures
        scheduler.scheduleAtFixedRate(() -> {
            try {
                if (guardedRuns.incrementAndGet() <= 2) {
                    throw new IllegalStateException("still failing");
                }
            } catch (RuntimeException e) {
                System.out.println("caught: " + e.getMessage());
            }
        }, 0, 50, TimeUnit.MILLISECONDS);

        Thread.sleep(400);
        scheduler.shutdownNow();

        // bare stays stuck at 1; guarded climbs close to the scheduled period count
        System.out.println("bare task stopped at:    " + bareRuns.get() + " run(s)");
        System.out.println("guarded task kept going: " + guardedRuns.get() + " runs");
    }
}

How it works

Scheduled Exception Suppresses Later Runs keeps everything in the class SchedulerExceptionSuppressor.

A guard precedes the IllegalStateException: bad state stops the flow there instead of continuing.

Using it

The run prints caught:, bare task stopped at:, guarded task kept going: — each prefix names the step that produced it.

Key statements

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
throw new IllegalStateException("boom on run " + bareRuns.get());
throw new IllegalStateException("still failing");

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
Validation comes first — `IllegalStateException` marks the failure, before any partial work happens.
What does Scheduled Exception Suppresses Later Runs print when run?
No setup needed: run the file and look for labeled lines like `caught:`, `bare task stopped at:`, `guarded task kept going:` in the output.