Android面试经典题——如何捕获(处理)未捕获的异常

直接上代码

1.自定义一个UncaughtExceptionHandler

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = "NoCrashHandler";
    private static CrashHandler sCrashHandler;
    private static Context sContext;

    public static CrashHandler getInstance() {
        if (sCrashHandler == null) {
            synchronized (CrashHandler.class) {
                if (sCrashHandler == null) {
                    sCrashHandler = new CrashHandler();
                }
            }
        }
        return sCrashHandler;
    }


    public void init(Context context) {  //初始化,把当前对象设置成UncaughtExceptionHandler处理器
        sContext = context;
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    /**
     * 有未处理的异常时
     *
     * @param thread
     * @param e
     */
    @Override
    public void uncaughtException(Thread thread, Throwable e) {
         Log.e(TAG, "uncaughtException, " + " 报错线程: " + thread.getName() + 
         " 线程id: " + thread.getId() + ",exception信息: "
                + e);
        String threadName = thread.getName();
        if ("UIThread".equals(threadName)) {
            Log.e(TAG, "根据Thread,可以保存异常信息");
        }
    }

2.自定义一个Application,初始化 CrashHandler

// 别忘记在AndroidManifest 指定application name属性
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        CrashHandler.getInstance().init(getApplicationContext());
    }
}

3 . 测试

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        test();
        crashTest();
    }

    private void crashTest() {
        String url = null;
        url.length();// 稳稳的一个NullPointerException
    }
}

4 . 结论,代码挂掉,也不会导致崩溃,并且收集报错信息

E/NoCrashHandler: uncaughtException,  报错线程: main 线程id: 1,exception信息: 
java.lang.RuntimeException: Unable to resume activity {gjy.com.mytest/gjy.com.mytest.MainActivity}: 
java.lang.NullPointerException: Attempt to invoke a virtual method on a null object reference

猜你喜欢

转载自blog.csdn.net/guojiayuan002/article/details/81135621