RSS

How to implement UncaughtExceptionHandler in Android

20 Sep

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);
		}
	}
}
Advertisements
 
Leave a comment

Posted by on September 20, 2014 in Android Source Code

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: