有没有办法在Android下的警报中显示自定义异常?

dgr*_*tin 6 user-interface alert android exception

我是Android新手开发者.我想知道是否存在一种在Android中侦听自定义异常并使用警报显示其文本的方法.谢谢.

Tre*_*hns 11

只需捕获所需的异常,然后创建一个包含异常内容的新AlertDialog.

import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;

public class HelloException extends Activity {
    public class MyException extends Exception {
        private static final long serialVersionUID = 467370249776948948L;
        MyException(String message) {
            super(message);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            doSomething();
        } catch (MyException e) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("MyException Occured");
            dialog.setMessage(e.getMessage());
            dialog.setNeutralButton("Cool", null);
            dialog.create().show();
        }
    }

    private void doSomething() throws MyException {
        throw new MyException("Hello world.");
    }
}
Run Code Online (Sandbox Code Playgroud)