I read in a C# introductory book that you shouldn’t catch an exception if you don’t know what to do with it. Thinking of that bit of advice while programming in Java, I sometimes find I do not know what to do with an exception, but I am forced to catch it or “percolate it up” to avoid a compile error. I’d rather not clutter methods with throws clauses all the way up the call tree so I have often resorted to “converting” the exception to a RuntimeException as in the following. Adding throws clauses to many methods for an exception that isn’t really “handled” (properly dealt with) seems verbose and distracting. Is the following bad style and if so what is a better way to deal with this?
try {
thread.join();
}
catch (InterruptedException e) {
Console.printwriter.format("%s\n", e.printStackTrace());
throw new RuntimeException();
}
Edit: Aside from the clutter, there’s another problem with the percolating exceptions: after code revisions you probably end up with some unnecessary throws clauses. The only way I know to clean them out is by trial and error: remove them and see if the compiler complains. Obviously, this is annoying if you like to keep the code clean.
The division in Java between checked and unchecked exceptions is somewhat controversial.
If you control the interface, adding a throws clause to the signature is usually the best way.
If you are in a situation where you cannot deal with an exception, but are not allowed to let it bubble up because of the checked exception signature, then wrapping the exception into an exception that you can rethrow (often a RuntimeException) is common practice.
In many cases, you’d want to use another checked exception, though, such as IOException or SQLException. But that is not always an option.
But in your example, include the original exception as the “cause”:
This may also remove the need for the logging (because this can also be deferred to someone who can handle the exception, and all information is still there).