Catch all type exceptions programming Android

来源:互联网 发布:金日十数据 编辑:程序博客网 时间:2024/04/30 10:45

转: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 getCausereport += "--------- 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);}}

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 别人给交错话费怎么办 联通流量不到账怎么办 卖家拒绝退款怎么办? 淘宝退款后红包怎么办 手机不能吃鸡怎么办? 在国外手机软件好多不支持怎么办 淘宝店拒绝退款怎么办 app没有退款资格怎么办 手机无法计步怎么办 抖音机型不支持怎么办 用nfc不支持卡片怎么办 移动怎么办省内流量包 手机交不了话费怎么办 淘宝快递不签收怎么办 快递买家不签收怎么办 淘宝退货未收货怎么办 淘宝退衣服运费怎么办 手机流量不到账怎么办 淘宝水果坏了怎么办 用微信充值话费充成空号了怎么办 苹果id被拉黑了怎么办 苹果app不退款怎么办 合同退款不退怎么办 微信充值q币被骗怎么办 小米手机存储空间不够怎么办 小米mix2s存储空间不够怎么办 进货一直没发票怎么办 魅蓝note5卡怎么办 电话费套餐花不了怎么办 墙和床头有间缝怎么办 床板里有虫子怎么办 松木床板味道大怎么办 寝室床板有虫子怎么办 胶合板当床板有气味怎么办 淘宝食品有问题怎么办 淘宝买东西碎了怎么办 被淘宝商家骚扰怎么办 闲鱼被别人拉黑怎么办 三无工厂抓到怎么办 淘宝买东西卖家不发货怎么办 打假人异地起诉怎么办