In some unexpected situations, we don't want to see program crashes. In this case, we can write logs in a file using uncaptured exceptions to record error information to prevent impact on user experience.
package com.home.testuncatch;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import com.home.testuncaughtexception.R;public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);MyUncaughtExceptionHandler.getInstance().init();setContentView(R.layout.main);Button btn = (Button) findViewById(R.id.main_btn);btn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String a = null;a.length();}});}}
MyUncaughtExceptionHandler:
Package com. home. testuncatch; import java. io. printWriter; import java. io. stringWriter; import java. lang. thread. uncaughtExceptionHandler; public class implements UncaughtExceptionHandler {private static MyUncaughtExceptionHandler instance; public synchronized static response getInstance () {if (instance = null) {instance = new response ();} return instance;} public void init () {// sets the current object as the default uncaptured exception processor Thread. setDefaultUncaughtExceptionHandler (this) ;}@ Overridepublic void uncaughtException (Thread t, Throwable e) {StringWriter stackTrace = new StringWriter (); e. printStackTrace (new PrintWriter (stackTrace); System. out. println (stackTrace); // you can write error logs in the file System. exit (10 );}}