java 未捕获 SQLiteConstraintException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3421577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 01:46:12  来源:igfitidea点击:

SQLiteConstraintException not caught

javaandroidexception-handlingtry-catch

提问by bogdan

What is the problem with this code? It doesn't catch the exception thrown by insertChild()method.

这段代码有什么问题?它不会捕获insertChild()方法抛出的异常。

childDbOps.open();
try {
    childDbOps.insertChild(child);
} catch (SQLiteException exception) {
    Log.i("error la inserare child", "on the next line");
    exception.printStackTrace();
} finally {
    childDbOps.close();
}

The error is:

错误是:

ERROR/Database(320): android.database.sqlite.SQLiteConstraintException: error code 19: 
constraint failed at com.android.dataLayer.DbAdapter.insertChild(DbAdapter.java:169) 
  at com.android.activities.ChildInsertActivity.onClick(ChildInsertActivity.java:203) 
  at android.view.View.performClick(View.java:2344) 

It is android sqlite. The line is when the insert method is called.

它是android sqlite。该行是调用插入方法的时间。

回答by Stephan Leroux

The SQLiteDatabase.insert() method is used in the cases where you want to handle database writes without unwinding the stack if a write fails. If you want to catch exceptions when inserting into the database, use the SQLite.insertOrThrow()method. It will throw an exception which you can then catch and handle.

SQLiteDatabase.insert() 方法用于在写入失败时您希望处理数据库写入而不展开堆栈的情况。如果要在插入数据库时​​捕获异常,请使用SQLite.insertOrThrow()方法。它将抛出一个异常,然后您可以捕获并处理该异常。

回答by Amarghosh

You're catching only exceptions of type SQLiteException. If the insertChildmethod throws any other exception, it won't be caught.

您只捕获 type 的异常SQLiteException。如果该insertChild方法抛出任何其他异常,则不会被捕获。

try {
   childDbOps.insertChild(child);
}
catch(SQLiteException exception) {
  Log.i("error la inserare child", "on the next line");
  exception.printStackTrace();
}
catch(AnotherException exception) {
  //handle it
}
//Catch them all here
catch(Exception exception) {
  //handle it: must handle it, don't just swallow it.
}
finally {
  childDbOps.close();
}

回答by Dead Programmer

@bogdan is there any other place u are calling insertChild(child); other than this place. did you put a trace in try block to know whether it comes to this block and print the trace like below.

@bogdan 是否还有其他地方您正在调用 insertChild(child); 除了这个地方。您是否在 try 块中放置了跟踪以了解它是否涉及此块并打印如下跟踪。

try { Log.i("comes here");
childDbOps.insertChild(child); }

尝试 { Log.i("来到这里");
childDbOps.insertChild(child); }

let me know.

让我知道。