SQLiteException没有被抓被抓、SQLiteException

2023-09-07 16:19:10 作者:别辞

我想抓住一个android.database.sqlite.SQLiteException:错误code 5:数据库已锁定异常:

I'm trying to catch an "android.database.sqlite.SQLiteException: error code 5: database is locked" exception with:

    try {
        db.insert("mytable", null, myvalues);
    } catch(SQLiteException e) {
        Log.d("My App", "caught");

        ...
    }

由于某些原因,我仍然得到错误,而中招并不在LogCat中显示出来。我试图捕捉一般的异常,但仍然无法正常工作。怎么了?

For some reason, I still get the error, and "caught" doesn't show up in LogCat. I tried catching a general "exception", but that still doesn't work. What's wrong?

更新 我发现这个问题,这是非常奇怪:因为某些原因改变db.insert()来db.insertOrThrow()作为goto10指出神奇固定的一切。该错误是从该行正在添加,但也许它不是抛出一个异常,只有崩溃的东西?

UPDATE I found the issue, and it is really weird: for some reason changing db.insert() to db.insertOrThrow() as goto10 stated magically fixed everything. The error was comming from that line, but maybe it wasn't throwing an exception and only crashing or something?

推荐答案

我不认为 .insert 将抛出一个异常。你可能只是看到正在被写它的日志信息时,它在内部捕获该异常。如果你想让它抛出一个异常时,插入失败,使用 .insertOrThrow 代替。

I don't believe that .insert will throw an exception. You're probably just seeing a log message that's being written by it when it catches the exception internally. If you want it to throw an exception when an insert fails, use .insertOrThrow instead.