Wednesday, February 1, 2017

How to implement UncaughtExceptionHandler in Android

If you do not handle a runtime exception in your program, the default behaviour will be to terminate the program and dump the call stacktrace on the console.

Java provides an elegant mechanism of handling Runtime Exceptions that you might have not handled in your program.
UncaughtExceptionHandler can be defined at three levels. From highest to lowest they are:
  1. Thread.setDefaultUncaughtExceptionHandler
  2. ThreadGroup.uncaughtException
  3. Thread.setUncaughtExceptionHandler
 package com.example.common;  
 import android.app.Activity;  
 public class TopExceptionHandler implements Thread.UncaughtExceptionHandler{  
   private Activity objApp;  
   public TopExceptionHandler(Activity app) {  
     objApp = app;  
     Thread.getDefaultUncaughtExceptionHandler();  
   }  
   @Override  
   public void uncaughtException(Thread thread, Throwable ex) {  
     // TODO Auto-generated method stub  
     try{  
       StackTraceElement[] arr = ex.getStackTrace();  
       String report = ex.toString();  
       String strStack = "";  
       strStack += "Stack trace: ";  
       for (int i=0; i<arr.length; i++){  
         strStack += "  "+arr[i].toString()+"\t";  
       }  
       // If the exception was thrown in a background thread inside  
       // AsyncTask, then the actual exception can be found with getCause  
       String strCause = "";  
       strCause += "Cause: ";  
       Throwable cause = ex.getCause();  
     }  
     catch(Exception ex1){  
       System.err.println(ex1);  
     }  
   }  
 }  
Now call TopExceptionHandler class as shown below:
 public class MyActivity extends AppCompatActivity{  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_layout);  
     new TopExceptionHandler(this);  
   }  
 }  
Run the app and check Logcat for all runtime exceptions.

No comments :

Post a Comment