Date: 2012jul6
OS: Android
Language: Java
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.
}
}