简体   繁体   English

在 Android SQLite 数据库 onCreate() 中重新抛出异常

[英]Rethrow Exception in Android SQLite Database onCreate()

Hey this is my onCreate method for a SQLiteDatabase that is of course called when a new database is created.嘿,这是我的 SQLiteDatabase 的 onCreate 方法,在创建新数据库时当然会调用它。 I want to catch any problem and log and then rethrow it for handling up above.我想捕获任何问题并记录下来,然后将其重新抛出以供上面处理。 However the compiler is not allowing me to rethrow the exception, complaining that it is not handled.但是编译器不允许我重新抛出异常,抱怨它没有被处理。 This is on the line that reads "throw e;".这是在写着“throw e;”的那一行。

@Override
public void onCreate(SQLiteDatabase db) {//arg0?
    db.beginTransaction();
    try {
        Checklist.createTable(db);
        Item.createTable(db);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(KnowUrStuffApp.TAG,"KusDBHelper.onCreate: " + e.getLocalizedMessage());           
        db.endTransaction();
        throw e;//SYNTAX ERROR: Unhandled Exception Type Exception
    }
}

Your problem is, that you're throwing a checked exception.您的问题是,您正在抛出一个已检查的异常。 This can only be done when this exception is只有在出现此异常时才能执行此操作

  1. directly caught and handled by a try/catch -blocktry/catch块直接捕获和处理
  2. or the exception is thrown "upwards" by adding throws SomeException to yourmethod-signature .或者通过将throws SomeException添加到您的方法签名来“向上”抛出异常。

However, in your case, you're overriding the onCreate() -method, which (in the base-class) does not throw a checked exception.但是,在您的情况下,您正在覆盖onCreate() -方法,该方法(在基类中)不会抛出已检查的异常。 Therefore, you can't override the method and add throws to the signature, because that wouldn't be an override anymore.因此,您不能重写该方法并将throws添加到签名中,因为那将不再是重写。

What you can do is, throw a RuntimeException upwards, which doesn't need to be added to the method signature:你可以做的是,向上抛出一个RuntimeException ,不需要在方法签名中添加:

Log.e(KnowUrStuffApp.TAG,"KusDBHelper.onCreate: " + e.getLocalizedMessage());           
db.endTransaction();
throw new RuntimeException(e); // Add the checked exception as the cause!

For more information on Exceptions (throwing and catching), see my blog-post: Catching practice有关异常(抛出和捕获)的更多信息,请参阅我的博客文章:捕获实践

public void onCreate(SQLiteDatabase db) throws Exception {//arg0?

EDIT : Thanks, throws*.编辑:谢谢,抛出*。

Change改变

public void onCreate(SQLiteDatabase db) {

to

public void onCreate(SQLiteDatabase db) throws Exception{

add throws Exception to your method.throws Exception添加到您的方法中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM