tyc*_*czj 7 java android unhandled-exception
我以前从来没有得过这个错误所以我不知道该做什么或它意味着什么
未处理的异常类型
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
}
Run Code Online (Sandbox Code Playgroud)
它给了我2个选项"添加抛出声明"和"环绕尝试/捕获".
我该怎么办?为什么?
Jon*_*ust 29
它表示您正在调用的方法是使用throws指令声明从Exception类派生的异常.当以这种方式声明方法时,您将被迫使用try/catch块处理throws异常或向方法声明添加相同的(对于相同的异常或超类型)语句.
一个例子.
我想foo在我的方法中调用一些方法bar.
这是foo定义:
public static void foo(String a) throws Exception {
// foo does something interesting here.
}
Run Code Online (Sandbox Code Playgroud)
我想打电话foo.如果我只是这样做:
private void bar() {
foo("test");
}
Run Code Online (Sandbox Code Playgroud)
...然后我会收到您遇到的错误. foo向全世界宣称它真的可能会决定扔掉它Exception,你最好准备好处理它.
我有两个选择.我可以改变bar的定义如下:
private void bar() throws Exception {
foo("test");
}
Run Code Online (Sandbox Code Playgroud)
现在我已经公开了我自己的警告,我的方法或我调用的方法可能抛出Exception我的方法的用户应该处理的.由于我已将责任推迟到我方法的调用者,因此我的方法不必处理异常本身.
如果可以的话,自己处理异常通常会更好.这带给我们第二个选择,try/catch:
private void bar() {
try {
foo("test");
} catch(Exception e) {
Log.wtf("MyApp", "Something went wrong with foo!", e);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我已经处理了潜在的Exception被抛出foo,编译器在抱怨.由于它已被处理,我不需要throws在我的bar方法中添加指令.