2013-10-03

Global UncaughtExceptionHandler for Android

I recently had the problem that LogCat omitted the stack-traces of exceptions in my code for some unknown reason (maybe thats due to my ORMLite-usage or something). Therefore I added this small method and called it directly beneath the super.onCreate(savedInstanceState) in my onCreate-method. It will provide you with messages and stack-traces to exceptions that otherwise would not be logged.

The method:
private void initUncaughtExceptionHandler() {
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
                Log.e("UncaughtException!", ex.getMessage());
                Log.e("UncaughtException!", Log.getStackTraceString(ex));
            }
        });
    }
Invocation of the method:
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initUncaughtExceptionHandler();
        setContentView(R.layout.main);
        
        [...]
    }