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
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021
Vault (Desktop) Version 0.72 ReleasedOctober 6, 2021
EBT Compass is Now Available for Android DevicesJune 2, 2021