Registering own Handler for unexpected exceptions

suggest change

This is how you can react to exceptions which have not been catched, similar to the system’s standard “Application XYZ has crashed”

import android.util.Log;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

 * Application class writing unexpected exceptions to a crash file before crashing.
public class MyApplication extends Application {

private static final String TAG = “ExceptionHandler”;

@Override public void onCreate() { super.onCreate();

// Setup handler for uncaught exceptions.
final Thread.UncaughtExceptionHandler defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread thread, Throwable e) {
        try {
        } catch (Throwable e2) {
            Log.e(TAG, "Exception in custom exception handler", e2);
            defaultHandler.uncaughtException(thread, e);


private void handleUncaughtException(Throwable e) throws IOException { Log.e(TAG, “Uncaught exception logged to local file”, e);

// Create a new unique file
final DateFormat dateFormat =  new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
String timestamp;
File file = null;
while (file == null || file.exists()) {
    timestamp = dateFormat.format(new Date());
    file = new File(getFilesDir(), "crashLog_" + timestamp + ".txt");
Log.i(TAG, "Trying to create log file " + file.getPath());

// Write the stacktrace to the file
FileWriter writer = null;
try {
    writer = new FileWriter(file, true);
    for (StackTraceElement element : e.getStackTrace()) {
} finally {
    if (writer != null) writer.close();

// You can (and probably should) also display a dialog to notify the user



Then register this Application class in your AndroidManifest.xml:

<application android:name="de.ioxp.arkmobile.MyApplication" >

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents