3

I have a global exception handler routine which wraps some exceptions in runtime exceptions

Like this

public class ExceptionHandler
{
public static void handle(){
    throw new RuntimeException(e);
}
}

In the ExceptionHandler class I also have a static constructor

static
  {
    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler()
    {
      @Override
      public void uncaughtException(Thread thread, Throwable throwable)
      {
        Throwable t;
        t = throwable;
        if (throwable.getCause() != null)
          t = throwable.getCause();
        Log.e(t.getClass().getName(), t.getMessage(), t);
      }
    };
    Thread.currentThread().setUncaughtExceptionHandler(h);
    Thread.setDefaultUncaughtExceptionHandler(h);
  }

Problem is, after throwing a RTE it does not enter the UncaughtExceptionHandler. Why?

BTW, I can't put it into the main method because there is no main in my Android program.

Roman C
  • 49,761
  • 33
  • 66
  • 176
cdbeelala89
  • 2,066
  • 3
  • 28
  • 39
  • see [here](http://stackoverflow.com/questions/2764394/ideal-way-to-set-global-uncaught-exception-handler-in-android) – linski Jan 10 '13 at 09:57
  • I think the code in static block is not executed, because ExceptionHandler isn't inited because no one uses ExceptionHandler class. [read this post](http://stackoverflow.com/questions/3560103/best-way-to-force-a-java-class-to-be-loaded). You can extend android's [Application](http://developer.android.com/reference/android/app/Application.html) class and place this code there, Application class' constructor is some kind of analog of "main" function. – Leonidos Jan 10 '13 at 10:00

2 Answers2

1

You can subclass Application class and init your ExceptionHandler in onCreate() method.

public class YourApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
    }
}

and implement your exception handler there

private class ExceptionHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread thread, Throwable throwable) {
        processUncaughtException(thread, throwable);
    }
}

You may also want to maintain the default exception handler so you can do it before setting it

defaultExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Taras Leskiv
  • 1,835
  • 15
  • 33
0

The static initializer block only gets executed when the class is loaded by the ClassLoader. I'm not an expert in Android but I think you can initialize the exception handler in your main activity class. Just use a static initializer block like you have here or use the Activity lifecycle methods like onCreate. There is also another option suggested here by Leonidos that might be best for this kind of initializations: Extend the Application class and put your code there.

Community
  • 1
  • 1
bruno conde
  • 47,767
  • 15
  • 98
  • 117