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.
If the brackets don't all match up, the result is a compile time error. The fix to this compile error is to add a leading round bracket after the println to make the error go away: int x = 10; System.
Throwing an exception is as simple as using the "throw" statement. You then specify the Exception object you wish to throw. Every Exception includes a message which is a human-readable error description. It can often be related to problems with user input, server, backend, etc.
overridden method of subclass may not throw any exception.
Checked exceptions are also known as compile-time exceptions as these exceptions are checked by the compiler during the compilation process to confirm whether the exception is handled by the programmer or not. If not, then the system displays a compilation error.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With