Dave's Brain

Browse - Programming Tips - How can my app suppress any possible Force Closes?

Date: 2012jul6
Platform: Android

Q.  How can my app suppress any possible Force Closes?

A.  On Android, a Force Close is caused by an uncaught exception.
So you can wrap questionable code in:

try { myCodeThatMayCrash(); } catch (Exception ex) { // Do something. eg log }
Or you can do:
Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler());
near the start of your app - eg onCreate() Where you write TopExceptionHandler - eg:
class TopExceptionHandler implements Thread.UncaughtExceptionHandler { private Thread.UncaughtExceptionHandler defaultUEH; TopExceptionHandler() { // Constructor this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler(); } void uncaughtException(Thread t, Throwable e) { // It makes sense to log something now. // You can display a simple dialog or toast message. // // In theory you can do anything here but // there are only two reasonable choices: // - Stop the app / exit // eg: // System.exit(666); // OR // - Pass control to the system's regular handler. // eg: // defaultUEH.uncaughtException(t, e); // // Again, its almost always not a good idea for your app // to continue on as if the exception had not occured. } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.