将致命的崩溃变成非致命的崩溃报告

时间:2014-08-05 15:50:21

标签: java android nullpointerexception crash fatal-error

有问题的代码:

final GenericAsyncTask task = new GenericAsyncTask();

        task.background = new Runnable() {
            public void run() {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(GCMIntentService.this.host);
                String addremove = "add";
                if(register == false) addremove = "remove";

                try {
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
                    nameValuePairs.add(new BasicNameValuePair("cmd", addremove));
                    nameValuePairs.add(new BasicNameValuePair("subscription_key", SUBSCRIPTION_KEY)); // unique per app
                    nameValuePairs.add(new BasicNameValuePair("token", str));
                    nameValuePairs.add(new BasicNameValuePair("os_family", "android"));
                    if(addremove.equals("remove")) nameValuePairs.add(new BasicNameValuePair("hard", "" + hard));
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs);
                    httppost.setEntity(entity);
                    Log.i(LCHApplication.TAG, "Name Value Pairs: " + nameValuePairs.toString());

                    // Execute HTTP Post Request
                    HttpResponse response = httpclient.execute(httppost);
                    task.result = EntityUtils.toString(response.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        };

        task.callback = new Runnable() {
            public void run() {
                Log.i(LCHApplication.TAG, "registration response: " + task.result.toString());
            }
        };

        task.execute();

其中大部分时间都很有效。但有时,task.result.toString();有时NULL会抛出java.lang.NullPointerException。我希望保持这种崩溃,因为我希望它能在崩解剂中报告,这样我才能看到它影响了多少人。如果我使用try / catch我可以扔什么以确保它是非致命的崩溃呢?这样它仍会报告崩溃,但它不会杀死该应用程序。

1 个答案:

答案 0 :(得分:10)

您不必抛出任何捕获的异常,您可以非常轻松地记录它们:

try {
  myMethodThatThrows();
} catch (Exception e) {
  Crashlytics.logException(e);
  // handle your exception here! 
}

来源:http://support.crashlytics.com/knowledgebase/articles/202805-logging-caught-exceptions