Class ExceptionHandler

java.lang.Object
org.javagi.base.ExceptionHandler

public class ExceptionHandler extends Object

Handles exceptions thrown by Java callback methods.

When a Java callback method that is invoked from native code throws an exception, the JVM will immediately crash. Java-GI therefore catches these exceptions.

By default, the exception is stored in a ThreadLocal field and will later be thrown (wrapped in a CallbackInvocationException), immediately after a native method call in the same thread has completed. This can optionally be disabled by setting the environment variable java-gi.discard-callback-exceptions to "true" (ignoring case).

When the environment variable java-gi.log-callback-exceptions is set to "true" (ignoring case), Java-GI will log the exception on stderr (using g_log() with level WARNING).

For performance reasons, the values of the two environment variables is cached, so the log/rethrow behavior cannot be changed during runtime.

  • Constructor Details

    • ExceptionHandler

      public ExceptionHandler()
  • Method Details

    • handleException

      public static void handleException(Throwable throwable, String source)

      Handles exceptions that were thrown in a Java callback method that was invoked from native code.

      When the environment variable java-gi.log-callback-exceptions is "true" (ignoring casse), the exception will be logged to stderr.

      Unless the environment variable java-gi.discard-callback-exceptions is "true" (ignoring case), the exception is stored to be thrown later.

      Parameters:
      throwable - the exception to handle
      source - the location where the exception occured
    • propagateExceptions

      public static void propagateExceptions() throws CallbackInvocationException

      When propagation of exceptions is not disabled with the envrionment variable java-gi.discard-callback-exceptions, and an exception was stored with handleException(Throwable, String), the exception is wrapped in a CallbackInvocationException and thrown.

      Note: The cause of the exception points to the actual location where the exception occured, while the outer CallbackInvocationException is thrown by the first method that completed in the same thread where the original exception occured. For example, when a GLib idle callback throws an exception, it will be rethrown from a completely unrelated callsite that just happened to be scheduled after the idle callback on the GLib main loop.

      Throws:
      CallbackInvocationException - wraps the exception that occured in a Java callback method.