7

我以前从未收到此错误,所以我不确定该怎么做或这意味着什么

未处理的异常类型OperationApplicationException

它出现在这段代码中:

public void putSettings(SharedPreferences pref){
    ArrayList<ContentProviderOperation> ops =
          new ArrayList<ContentProviderOperation>();

    ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
    .withSelection(Data.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(pref.getString(SmsPrefs.ID, ""))})
    .withValue(Data.MIMETYPE,"vnd.android.cursor.item/color")
    .withValue("data1",nColor).build());
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); //error


    ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
    .withSelection(Data.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(pref.getString(SmsPrefs.ID, ""))})
    .withValue(Data.MIMETYPE,"vnd.android.cursor.item/vibrate")
    .withValue("data1", nVibrate).build());
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops); //error

    ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
    .withSelection(Data.RAW_CONTACT_ID + "=?", new String[]{String.valueOf(pref.getString(SmsPrefs.ID, ""))})
    .withValue(Data.MIMETYPE, "vnd.android.cursor.item/sound")
    .withValue("data1", ringTonePath).build());
    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);//error
}

它给了我 2 个选项“添加抛出声明”和“用 try/catch 包围”。

我必须做什么,为什么?

4

1 回答 1

30

这意味着您正在调用的方法是使用从该类throws派生的异常的指令声明的。Exception当以这种方式声明方法时,您必须使用try/catch块来处理异常或在方法声明中添加相同的throws(针对相同的异常或超类型)语句。

一个例子。

我想foo在我的方法中调用一些方法bar

这是foo的定义:

public static void foo(String a) throws Exception {
    // foo does something interesting here.
}

我想打电话foo。如果我只是这样做:

private void bar() {
    foo("test");
}

...然后我会收到您遇到的错误。 foo向世界宣布它真的可能决定抛出一个Exception并且你最好准备好处理它。

我有两个选择。我可以将bar' 的定义更改如下:

private void bar() throws Exception {
    foo("test");
}

现在我已经公开了我自己的警告,即我的方法或我调用的某些方法可能会引发Exception我的方法的用户应该处理的问题。由于我已经将责任推给了方法的调用者,因此我的方法不必处理异常本身。

如果可以的话,最好自己处理异常。这将我们带到了第二个选项,即try/catch

private void bar() {
    try {
        foo("test");
    } catch(Exception e) {
        Log.wtf("MyApp", "Something went wrong with foo!", e);
    }
}

Now I've dealt with the potential Exception thrown by foo that the compiler was complaining about. Since it's been dealt with, I don't need to add a throws directive to my bar method.

于 2011-03-02T02:03:55.277 回答