{{announcement.body}}
{{announcement.title}}

Robust Exception Handling

DZone 's Guide to

Robust Exception Handling

Handle exceptions like a champ.

· Java Zone ·
Free Resource

Oh no, don't do this to me...

// Writing comment that exception is skipped
try {
    throw new IOException("Made up");
} catch (IOException e) {
    // skip it
}

// Logging and moving on
try {
    throw new IOException("Made up");
} catch (IOException e) {
    log.error("blah blah blah", e);
}

// Creating TODO instead of actually doing the job
try {
    throw new IOException("Made up");
} catch (IOException e) {
    // TODO - handler it (;
}


.... and still, I am finding those catch blocks inside various projects. This is a great way to suppress the problem — for a short period of time. A few weeks or months later, this will become a nightmare for developers. Walking through the old log files and trying to figure out what went wrong is definitely not that most people want to do. Therefore, let's avoid that.

The first rule is that catch blocks are here to handle exceptional situations. Logging exceptions and moving on is not considered as handling. The only case when it makes sense to suppress exception is during the closing of the resource after a prior exception (this case isn't covered within this article; if you are interested, then here is an old yet still very good blog post written by McDowell).

There are three basic patterns of how to handle exceptions: translate, retry, and recover.

Translate is often used when you have to deal with a checked exception, your method can't bubble it up, and recovery is not possible. In such cases, it is appropriate to translate it into a runtime exception and throw up. Then, the runtime exception is typically handled in the framework level. Retry is useful when dealing with unreliable services. It makes sense only if retrying makes sense fundamentally. The good example is retrying to overcome network interruptions. Recover is good when the strategy for doing that is defined. For example, you can write data to the local storage if sending over network fails. Of course, then it's necessary to define what to do with that file.

In addition, the mentioned patterns might be combined. Examples are as follows.

// Translate
try {
    throw new IOException("Made up");
} catch (IOException e) {
    throw new RuntimeException(e);
}

// Retry - give up after 5 tries
boolean end = false;
int count = 0;
while (end == false) {
    try {
        // Send message.
        if (true) {
            throw new MessagingException("Made up");
        }
        end = true;
    } catch (MessagingException e) {
        if (count >= 5) {
            // Give up after 5 tries.
            throw new RuntimeException("was not able to send message even after five tries", e);
        }
        ++count;
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e1) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e1);
        }
    }
}

// Recover - write to file if a transfer fails
try {
    // Send message.
    throw new MessagingException("Made up");
} catch (MessagingException e) {
    try {
        // Write to file.
        throw new IOException("Made up");
    } catch (IOException e1) {
        // No more recovery if writing to file fails.
        throw new RuntimeException(e1);
    }
}


If everything fails, then this way will at least guarantee that you will be aware of the problem. In addition, it will provide you always the true cause of the issue; therefore, you will be able to quickly identify where the problem is!

Happy handling!

Topics:
java ,programming ,exception handling ,translate ,recover ,retry ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}