Fork us on GitHub

Thread Errors

Better handling of errors in a multi-threded environment
Thread Errors

Thread Errors

I wrote before about EasyThread which makes it much easier to write multi-threaded code in Codename One. One problem in that scenario was the inability to define a generic exception handler for that scenario.

With the current version of Codename One we now have a new generic error handling API for easy threads:

public void addErrorListener(ErrorListener err);
public static void addGlobalErrorListener(ErrorListener err);

These methods add a callback for error events, either globally or for a specific thread. Notice that these methods aren’t thread safe and should be invoked synchronously. So make sure to invoke them only from one thread e.g. the EDT.

These methods must never be invoked from within the resulting callback code!

So you can’t do this:

t.addErrorListener((t, c, e) -> {
   // do stuff ...

   // this is illegal:
   t.removeErrorListener(listener);
});

The error listener interface looks like this:

public static interface ErrorListener<T> {
    /**
     * Invoked when an exception is thrown on an easy thread. Notice
     * this callback occurs within the thread and not on the EDT. This
     * method blocks the current easy thread until it completes.
     * @param t the thread
     * @param callback the callback that triggered the exception
     * @param error the exception that occurred
     */
    void onError(EasyThread t, T callback, Throwable error);
}

This should provide you with all the details you need to handle an error in a generic way.

Share this Post:

Posted by Shai Almog

Shai is the co-founder of Codename One. He's been a professional programmer for over 25 years. During that time he has worked with dozens of companies including Sun Microsystems.
For more follow Shai on Twitter & github.