Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching exceptions from another threads?

I am writing an app that will make use of multiple threads. There is main thread that is launching another threads. What i want to acomplish is when one of the launched threads throws an exception, the main thread should stop launching threads. It looks more or less like this:

class SomeClass {
boolean launchNewThread = true;
public static void main() {
    while (launchNewThread) {
        try {
            AnotherClass.run();
        } catch (CrossThreadException e) {
            launchNewThread = false;
        }
    }
}
}

class AnotherClass implements Runnable {
    public void run() {
        if (a=0) throw new CrossThreadException();
}

}

like image 220
BartoszCichecki Avatar asked Mar 08 '26 12:03

BartoszCichecki


2 Answers

You should do it yourself - catch the exception and pass it somehow into the launching thread.

Also, there is Future concept, which does it already. You should launch your threads as futures and check isDone(), and catch ExecutionException from get(), this exception will be thrown if a future's task thrown an exception.

like image 138
kan Avatar answered Mar 10 '26 01:03

kan


You can also use a listener as described in How to throw a checked exception from a java thread?

When an exception is thrown inside one of the child threads, you could call a method like listener.setLaunchNewThread(false) from the child thread which will change the value of your boolean flag in the parent thread.

On a side note, calling AnotherClass.run() does not start a new thread but only call the run method from AnotherClass within the same thread. Use new Thread(new AnotherClass()).start() instead.

like image 27
laguille Avatar answered Mar 10 '26 01:03

laguille