How to handle UncaughtException in Android

19 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:


package com.example.common;


public class TopExceptionHandler implements Thread.UncaughtExceptionHandler{
	private Activity objApp;

	public TopExceptionHandler(Activity app) {
		objApp = app;

	public void uncaughtException(Thread thread, Throwable ex) {
		// TODO Auto-generated method stub
			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){

Leave a comment

Posted by on September 19, 2014 in Android Source Code


Tags: ,

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: