Nightloewe
Nightloewe

Reputation: 1098

Java respond to application when SQLException is happening

I currently have a database class containing all my methods for retrieving data from the SQL Database. A method looks like:

@Override
public void setGlobalSetting(Setting setting) {
    if(setting.getId() == 0) {
        try {
            PreparedStatement ps = this.conn.prepareStatement("INSERT INTO BotSettings(guildId, settingKey, settingValue) VALUES(?, ?, ?)");
            ps.setLong(1, -1);
            ps.setString(2, setting.getKey());
            ps.setString(3, setting.getValue());

            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    } else {
        try {
            PreparedStatement ps = this.conn.prepareStatement("UPDATE BotSettings SET settingValue = ? WHERE guildId = ? AND settingKey = ?");
            ps.setString(1, setting.getValue());
            ps.setLong(2, -1);
            ps.setString(3, setting.getKey());

            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

The problem is that I can't tell my application when a SQLException happened, so that the application may respond to the users that the application failed to save data. How can I realize a method that can tell the application about failure. I thought of using Consumer to tell success and failure, but are there other ways?

Upvotes: 0

Views: 49

Answers (1)

Stephen C
Stephen C

Reputation: 718748

I thought of using Consumer to tell success and failure, but are there other ways?

You don't need to catch SQLException. You could conceivably allow it to propagate to a higher level where it can be handled appropriately.

Alternatively, you could throw a new exception. For example:

public void setGlobalSetting(Setting setting) throws MyException {
    if(setting.getId() == 0) {
        try {
            ...
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new MyException("Cannot set setting due to database error", e);
        }
    } else {
        ...
    }
}

There may be an existing exception that is sensible throw in this context. If not, declare your own exception class.

If you think that the caller needs to try to recover from this, a checked exception would be appropriate. Otherwise use an unchecked exception.


The takeaway is that your code shouldn't catch an exception unless it is able to deal with it. Printing a stacktrace and continuing is rarely the correct way to deal with an exception.

Upvotes: 2

Related Questions