Programming, Software and Code

Software Anti-Pattern: The Exception Repeater



Since I've seen this pattern several times in a software project I'm trying to maintain, I've decided to give it a name: The Exception Repeater anti-pattern. Here's a particularly succinct implementation of it, direct from the repo:

public static void ValidateData() {
try {
ValidateDataInner();
} catch (Exception e) {
throw e;
}
}

Since I've seen this exact thing several times in the codebase today, I'm wondering if maybe it has some kind of magical benefit or side-effect that I'm not aware of. The only benefit that I can think of is that an unintelligent programmer can claim to be programming "defensively", or something like that.

Comments

As written here, it obviously has no purpose at all. But slightly modified, I can think of at least two cases where I use it.

1. Converting checked exception to unchecked -- applicable only to languages distinguishing checked and unchecked exceptions.

public void validateData() {
try {
doValidateData(); // throws Exception
} catch (Exception e) {
throw RuntimeException(e);
}
}

2. Logging or some other exception processing.

public void validateData() throws Exception {
try {
doValidateData(); // throws Exception
} catch (Exception e) {
log.warn("failed", e);
throw e;
}
}

The advantage is very little, but it is there -- separating exception processing from "real meat". Not extremely important, but I kinda like it this way.

Yes, you're right. re-throwing isn't a bad thing, so long as you make som kind of change. Throwing the exact same exception in the exact same way is never useful

A coworker of mine justifies this as documentation that the code might throw an exception. He says it's good practice to indicate to future programmers that you knew about possible exceptions but decided explicitly not to deal with them.

I'm not entirely convinced, because my assumption is that any code can throw exceptions at any time. Which means you have to put try/catch everywhere?



This entry was originally posted on Blogger and was automatically converted. There may be some broken links and other errors due to the conversion. Please let me know about any serious problems.