Eric Bergman-Terrell's Blog

Android Programming Tip: Catch and Log Uncaught Exceptions
May 16, 2011

As I developed my new Android application, Vault 3 for Android, I found it very convenient to catch and log uncaught exceptions. Here's how you can catch them in your app.

Step 1: Create a class inherited from UncaughtExceptionHandler, and implement the uncaughtException method:

public class CustomUncaughtExceptionHandler implements UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread thread, Throwable tr) {
String logMessage = String.format("CustomUncaughtExceptionHandler.uncaughtException: Thread %d Message %s", thread.getId(), tr.getMessage());

Log.e(StringLiterals.LogTag, logMessage);

tr.printStackTrace();

if (VaultPreferenceActivity.isUncaughtExceptionLoggingEnabled()) {
PrintWriter printWriter = null;

try {
printWriter = new PrintWriter(new FileWriter("/sdcard/Vault3Log.txt", true));

logMessage = String.format("%s\r\n\r\nThread: %d\r\n\r\nMessage:\r\n\r\n%s\r\n\r\nStack Trace:\r\n\r\n%s",
     new Date(), 
     thread.getId(), 
     tr.getMessage(), 
     Log.getStackTraceString(tr));

printWriter.print(logMessage);
printWriter.print("\n\n---------------------------------------------------------------------------\n\n");
}
catch (Throwable tr2) {
}
finally {
if (printWriter != null) {
printWriter.close();
}
}
}
}

Step 2: Call Thread.setDefaultUncaughtExceptionHandler with your UncaughtExceptionHandler-derived object early in the application lifespan.

Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());

Since I want to start catching uncaught exceptions as early as possible in my app's lifespan, I implemented a custom Application class for Vault 3 for Android:

public class VaultApplication extends Application {
@Override
public void onCreate() {
super.onCreate();

Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());

Log.i(StringLiterals.LogTag, "VaultApplication.onCreate");
}

...

This application class is specified in my AndroidManifest.xml file:

...
    <application 
    android:name="com.ericbt.Vault3.VaultApplication"  
...

If you need to keep track of important notes, with optional strong encryption, check out Vault 3 for Android. Thanks!

Keywords: Android, UncaughtExceptionHandler, exceptions, Application, AndroidManifest.xml, setDefaultUncaughtExceptionHandler

Reader Comments

Comment on this Blog Post

Recent Posts

TitleDate
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015
Node.js / Express Programming Tip: Detect and Fix Memory LeaksOctober 27, 2015