Code That Made Me Cry, #CTMMC™

95% of all code makes me cry. The other 5% are white space.

JDBC Exception Handling (Java, #37 / 50)

// PostgreSQL:
@Override
public void manageException(SQLException ex)
throws ExceptionDBDuplicateEntry, 
       ExceptionDBEntryReferencedElsewhere,
       ExceptionDBUnknownError {
    if (ex.getSQLState() == null) {
        ex = (SQLException) ex.getCause();
    }
    if (ex.getSQLState().equals(UNIQUE_VIOLATION)) {
        throw new ExceptionDBDuplicateEntry();
    } else if(ex.getSQLState().equals(FOREIGN_KEY_VIOLATION)) {
        throw new ExceptionDBEntryReferencedElsewhere();
    } else {
        DAOPackage.log(ex);
        throw new ExceptionDBUnknownError(ex);
    }
}

// SQLite
@Override
public void manageException(SQLException ex) 
throws ExceptionDBDuplicateEntry, 
       ExceptionDBEntryReferencedElsewhere,
       ExceptionDBUnknownError {
    String message = ex.getMessage().toLowerCase();
    if(message.contains("sqlite_constraint")) {
        if(message.contains("is not unique")) 
            throw new ExceptionDBDuplicateEntry();
        else if(message.contains("foreign key constraint failed")) 
            throw new ExceptionDBEntryReferencedElsewhere();
        else {
            DAOPackage.log(ex);
            throw new ExceptionDBUnknownError(ex);
        }
    } else {
        DAOPackage.log(ex);
        throw new ExceptionDBUnknownError(ex);
    }
}
        

All these years after JDBC's inception, people still think that parsing localised exception messages is a good idea to detect exception semantics. Sigh. And don't get me started on the exception names used in this example.

Source: http://java.dzone.com/articles/postgresql-sqlite-journey?page=0,2

comments powered by Disqus

Submit your own Code That Made You Cry

Send us your own example of code that made you cry! Please include:

Send the above to ctmmc@datageekery.com. All accepted submissions will be licensed as CC BY-SA 3.0. Submit only code of a compatible license.

Note that we may choose not to publish some submissions if we feel they're not appropriate. We hope you understand.

Don't let your SQL code make you cry!

Use jOOQ, instead of JDBC.

jOOQ generates Java code from your database and lets you build typesafe SQL queries through its fluent API.

Don't let your SQL code make you cry! Get back in control of your SQL with jOOQ.