No compiler error/warning for not catching/throwing exception
Asked Answered
U

1

7

I don't understand why the compiler does not warn me about not catching or throwing an SQLException. Here's the situation:

I have defined this interface:

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

Then I created this class that implements the given interface:

public class SqliteHelper extends SQLiteOpenHelper implements
        GenericDatabaseManager {

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

And finally I'm calling this SqliteHelper.createTables() from here:

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() returns a GenericDatabaseManager instance. But the compiler shows no error on dbCoreModel.getManager().createTables(dbModel); line, although this line throws an SQLException.

Does anyone have an idea about why is this happening? Thanks in advance.

EDIT: about SQLException does not need to be catched because it's a RuntimeException. This is not true. Here's an example:

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

}

The compiler DOES show an error in i.throwsSQLException(); in this case.

Unific answered 22/11, 2012 at 9:47 Comment(2)
Useless to ask whether "Previous code..." contains a try { and "More code..." contains a } catch (SQLException e) {, right ? :DGrunter
Then, as PC. answered, you're not using java.sql.SQLException, but android.database.SQLException. Check your imports.Grunter
R
13

android.database.SQLException is a runtime exception.

In java it is not necessary to catch or declare throws for runtime exceptions. Read a detailed description about RuntimeExceptions in java here

Roryros answered 22/11, 2012 at 9:54 Comment(5)
SQLException is not a runtime exception.Unific
android.database.SQLException is a RuntimeException, java.sql.SQLException isn't.Tinner
the question is about android.database.SQLException and not java.sql.SQLExceptionRoryros
The questio or the answer do not specfie what SQLException is about.Execratory
@onof I am using Android JUnitUnific

© 2022 - 2024 — McMap. All rights reserved.