B
B
BRONNER2014-10-26 19:14:07
Java
BRONNER, 2014-10-26 19:14:07

Are empty catch blocks bad?

Here is a simplified version of how I use Try-Catch

class Database {
    public void addRow() throws SQLException {
        try { /* Add row */ }
        catch(SQLException e) {
            log.error(e);
            throw e;
        }
    }
}

class Context1 {
    public void doSomething(Database db) throws SQLException {
        db.addRow(); //If throws exception then main exception handler executes sendMessage("failed");
        sendMessage("success");
    }
}

class Context2 {
    public void doSomething(Database db) {
        try { db.addRow(); }
        catch (SQLException ignored) {}
    }
}

I would like to avoid exception rethrows in order to avoid empty catch blocks in the second situation, when it is not necessary to notify anywhere except the console, but then it becomes impossible to handle the first situation, when it is necessary to notify the user about the failed operation.
How to be in such a situation?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2014-10-26
@BRONNER

Actually, exception handling and the exceptions themselves are evil, which should happen very rarely, it's better to check the parameters yourself, and handle all exceptions at the very top. Even better, use an object of type context , where to drive all your errors and pass it, for example, as a thread variable. Well, if an exception has already happened, then it really should be an exceptional situation, such as a transaction violation or a broken connection. Avoid situations where exceptions are used for validation and parameter conversion - this is evil, it's better to add a couple of ifs or do introspection with a case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question