UncaughtException in Android

One of the nightmares for developer is an unhandled exception in an application. When we are developing an application, we already use try-catch blocks to handle exceptions. But, time to time we miss something on code part. Imagine that, we are reading string data from database and compare it with some values. If we receive data from database as a null it means NullPointerException will be thrown.
    
    String dummyString = null;

    if (dummyString.equals("something")) {
        int dummyInt = 1;
    }
In lot of programming languages, generally we create a general exception handling function for this kind of case. And when we catch exception with this function, we can log it, save it to somewhere, mail to somebody, etc.

What about Android application? Yes, "Force close" dialog box. If our application throws an unhandled exception, Android shows a "Force Close" dialog box and close our application. What happened? How can we see an exception?

Let's start.

First, we create our generic exception handler class which is implemented from UncaughtExceptionHandler
    
public class UnhandledExceptionHandler implements UncaughtExceptionHandler {

    private UncaughtExceptionHandler _defaultUncaughtExceptionHandler;

    public UnhandledExceptionHandler() {
        _defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        _defaultUncaughtExceptionHandler.uncaughtException(thread, ex);
    }

}
and we set it as a default uncaught exception handler in Application onCreate event
    
public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
  
        Thread.setDefaultUncaughtExceptionHandler(new UnhandledExceptionHandler());
    
    }
}


That's all. Now, we can catch unhandled exception in
    
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        _defaultUncaughtExceptionHandler.uncaughtException(thread, ex);
    }
function and we can do whatever we want.
    
    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        // write exception to log file
        // write exception to database
        // send exception to developer as an e-mail
        // ...

        _defaultUncaughtExceptionHandler.uncaughtException(thread, ex);
    }

0 comments:

Post a Comment