首页 文章

未处理的异常类型错误

提问于
浏览
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个选项“添加抛出声明”和“环绕尝试/捕获” .

我该怎么办?为什么?

1 回答

  • 28

    这意味着您正在调用的方法使用 throws 指令声明从 Exception 类派生的异常 . 当以这种方式声明方法时,您将被迫使用 try/catch 块处理异常,或者在方法声明中添加相同的 throws (对于相同的异常或超类型)语句 .

    一个例子 .

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

    这是 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 . 由于我是've deferred responsibility to my method'的调用者,我的方法不必处理异常本身 .

    如果可以的话,自己处理异常通常会更好 . 这将我们带到第二个选项 try/catch

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

    现在我已经处理了编译器抱怨的 foo 抛出的潜在 Exception . 既然's been dealt with, I don' t需要在我的 bar 方法中添加 throws 指令 .

相关问题