Catch all type exceptions programming Android

转: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);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值