转:http://stackoverflow.com/questions/5773993/catch-all-type-exceptions-programming-android
Q:
I'm developing an application for Android OS. Since this is my first application, I think I've committed some programming mistakes cause I hardly can trace bugs back to their causes. Thus, I was guessing, while i'm trying to fix bugs, is there a way to catch ALL types of exception in my entire activity lifecycle with one try-catch?
That would be awesome, i'm getting bored watching my galaxy S say :"Sorry the application App has stopped unexpectly" :(
A:
You can use an UncaughtExceptionHandler to possibly prevent some crashes. I use one, but only to print stack traces to a file, for when I'm debugging an app on a phone away from my computer. But I pass on the uncaught exception to the default Android UncaughtExceptionHandler after I've done that, because I want Android to be able to handle it correctly, and give the user the opportunity to send me a stack trace.
Code:
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
public class SRSDexception implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler defaultUEH;
private Activity app = null;
public SRSDexception(Activity app) {
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
this.app = app;
}
public void uncaughtException(Thread t, Throwable e)
{
StackTraceElement[] arr = e.getStackTrace();
String Raghav =t.toString();
String report = e.toString()+"\n\n";
report += "--------- Stack trace ---------\n\n"+Raghav;
for (int i=0; i<arr.length; i++)
{
report += " "+arr[i].toString()+"\n";
}
report += "-------------------------------\n\n";
// If the exception was thrown in a background thread inside
// AsyncTask, then the actual exception can be found with getCause
report += "--------- Cause ---------\n\n";
Throwable cause = e.getCause();
if(cause != null) {
report += cause.toString() + "\n\n";
arr = cause.getStackTrace();
for (int i=0; i<arr.length; i++)
{
report += " "+arr[i].toString()+"\n";
}
}
report += "-------------------------------\n\n";
try {
FileOutputStream trace = app.openFileOutput(
"stack.trace", Context.MODE_PRIVATE);
trace.write(report.getBytes());
trace.close();
} catch(IOException ioe) {
// ...
}
defaultUEH.uncaughtException(t, e);
}
}