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

Jac*_*nkr 2 java crash android nullpointerexception 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();
Run Code Online (Sandbox Code Playgroud)

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

Edu*_* B. 10

您不必抛出任何捕获的异常,您可以非常容易地记录它们,如下所示:

try {
  myMethodThatThrows();
} catch (Exception e) {
  Crashlytics.logException(e);
  // handle your exception here! 
}
Run Code Online (Sandbox Code Playgroud)

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