Android exception handling best practice?

后端 未结 3 1812
生来不讨喜
生来不讨喜 2020-11-29 16:26

If my app crashes, it hangs for a couple of seconds before I\'m told by Android that the app crashed and needs to close. So I was thinking of catching all exceptions in my a

3条回答
  •  青春惊慌失措
    2020-11-29 16:44

    You could just use a generic alert dialog to quickly display error messages. For example...

    //******************************************
    //some generic method
    //******************************************
    private void doStuff()
    {       
        try
        {
            //do some stuff here
        }
        catch(Exception e)
        {
            messageBox("doStuff", e.getMessage());
        }
    }
    
    
    //*********************************************************
    //generic dialog, takes in the method name and error message
    //*********************************************************
    private void messageBox(String method, String message)
    {
        Log.d("EXCEPTION: " + method,  message);
    
        AlertDialog.Builder messageBox = new AlertDialog.Builder(this);
        messageBox.setTitle(method);
        messageBox.setMessage(message);
        messageBox.setCancelable(false);
        messageBox.setNeutralButton("OK", null);
        messageBox.show();
    }
    

    You could also add other error handling options into this method, such as print stacktrace

提交回复
热议问题