Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dealing with catastrophic exceptions

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.

like image 736
H2ONaCl Avatar asked Nov 22 '12 10:11

H2ONaCl


2 Answers

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":

 throw new RuntimeException(e);

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).

like image 72
Thilo Avatar answered Sep 30 '22 13:09

Thilo


I like the advice in Joshua Bloch's Effective Java 2nd edition - Throw exceptions appropriate to the abstraction (Item 61).

That is, when faced with a series of exceptions you wish to "percolate" out of your method, consider whether the exceptions should be re-wrapped with something that makes more semantic sense for your method.

Such an approach often has the pleasing side effect of combining several lower-level exceptions into a single higher-level exception.

like image 31
Duncan Jones Avatar answered Sep 30 '22 14:09

Duncan Jones