没有编译器错误/警告没有捕获/抛出异常

时间:2012-11-22 09:47:36

标签: java android sqlexception

我不明白为什么编译器不会警告我不要捕捉或抛出SQLException。情况如下:

我定义了这个界面:

public interface GenericDatabaseManager {
    public void createTables(DataBase model) throws SQLException;
}

然后我创建了这个实现给定接口的类:

public class SqliteHelper extends SQLiteOpenHelper implements
        GenericDatabaseManager {

    @Override
    public void createTables(DataBase model) throws SQLException {
        // Code that throws SQLException
    }

最后我从这里调用了这个SqliteHelper.createTables():

public class DatabaseManager extends CoreModule {
    private boolean createUpdateDB(final String dbString, final String appId) {
        // Previous code...

        if (oldVer == -1) {
            dbCoreModel.addModel(dbModel);
            dbCoreModel.getManager().createTables(dbModel);
            return true;
        }

        // More code...
    }

}

dbCoreModel.getManager()会返回GenericDatabaseManager个实例。但是编译器在dbCoreModel.getManager().createTables(dbModel);行上没有显示错误,尽管此行会抛出SQLException

有没有人知道为什么会这样?提前谢谢。

编辑:大约SQLException不需要被捕获,因为它是RuntimeExceptionThis is not true。这是一个例子:

import java.sql.SQLException;

interface Interface {
    public void throwsSQLException() throws SQLException;
}

class Test implements Interface {

    @Override
    public void throwsSQLException() throws SQLException {
        throw new SQLException();
    }
}

public class Main {

    public static void main(String[] args) {
        Interface i = new Test();
        i.throwsSQLException();
        System.out.println("Finished");
    }

}

在这种情况下,编译器在i.throwsSQLException();中显示错误。

1 个答案:

答案 0 :(得分:12)

android.database.SQLException是运行时异常。

在java中,没有必要捕获或声明运行时异常的抛出。阅读有关java RuntimeExceptions

here的详细说明