kzidane
kzidane

Reputation: 763

Why can't exception handling deal with asynchronous events?

  • Exception handling is not designed to process problems associated with asynchronous events (e.g., disk I/O completions, network message arrivals, mouse clicks and keystrokes), which occur in parallel with, and independent of, the program’s flow of control.

How is exception handling not designed to handle asynchronous events? Why is this the case?

I'll be thankful if you enhanced your answers by quite detailed examples.

Upvotes: 1

Views: 179

Answers (1)

assylias
assylias

Reputation: 328598

I think that is a misleading statement.

Asynchronous work is done through threads in Java (or processes but that is a different matter).

What is true is that if you start a thread and an exception is thrown in that thread, you won't be able to catch it from your main thread.

But nothing prevents you from handling exceptions in that new thread.

Example - the code below prints Exception was raised in the thread but we can still handle it:

public static void main(String[] args) throws Exception {
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            throw new RuntimeException("oops");
        }
    });
    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println("Exception was raised in the thread but we can still handle it");
        }
    });

    t.start();
}

Alternatively, you can add some exception catching logic within the Runnable itself.

Upvotes: 2

Related Questions