Uncaptured andoid processing exception

Source: Internet
Author: User

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


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.