SQLiteException not being caught

2020-04-08 12:29发布

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");

        ...
    }

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?

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?

4条回答
闹够了就滚
2楼-- · 2020-04-08 12:56

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.

查看更多
时光不老,我们不散
3楼-- · 2020-04-08 13:02

Try this

try { 

} catch( SQLiteException e) {
     Log.e("My App",e.toString(), e);
}
查看更多
Evening l夕情丶
4楼-- · 2020-04-08 13:07

If that catch block is failing to catch the exception then either it isn't being thrown inside that particular try block, or you've got the wrong exception. The fact that it still doesn't work if you catch Exception says that it is the former problem.

So you need to find out where the exception is really being throw. I'd try changing the logging configurations to get LogCat to log full exception stacktrace. That should tell you where it was thrown. If you can't do that, then you'll need to find this using a debugger ... or by trawling through your applications source code to find where the exception is being logged.

(The other possibility is that the catch block is catching the exception, but you've got your logging configs set up to discard "debug" log events.)

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-04-08 13:14

The exception is probably thrown when you open the database, not when you insert a new row.

查看更多
登录 后发表回答