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 {
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);


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(), 

catch (Throwable tr2) {
finally {
if (printWriter != null) {

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 {
public void onCreate() {

Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler());

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


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


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

How to decompile Java code with JetBrains IntelliJ IDEA (2018.2.3, Windows 10)October 5, 2018
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