Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Note that people now consider that as a mistake

Correction: Some people. Java's checked and unchecked exception approach is quite nice if used judiciously. It certainly beats checking for error after every function call (default: mostly people ignore error codes) and you even get typed errors so you can trivially incorporate exception handling in the conceptual design as a first class design element.

I am frankly not sure how people get confused about "control flow" and exceptions. (In decades of Java programming the only thing that can still cause minor reading/writing nuisance are generic types and type erasure in over elaborate generic code.)



The greatest secret of exceptions is that in most cases you don't need to catch them. What should really be on your fingertips is

   try {
      ... something ... 
   } finally {
      ... clean up ...
   }
this (plus try-with-resources) is the genius of exceptions. The tragedy of exceptions in Java is that checked exceptions convert the above to

   try {
     ... something ...
   } catch(ACheckedExceptionThatHasNothingToDoWithThisCode x) {
      throw new SomeOtherCheckedExceptionToPleaseTheCompiler(x)
   } finally {
      ... do what has to be done ...
   }
with the variations of

   throw new AnUncheckedExceptionSoIDontVandalizeMyCodeMore(x)
and

   catch(...) {
      // i forgot to rethrow the exception but at least the compiler isn't complaining
   }
as well as

   // i forgot to add a finally cause because I was writing meaningless catch clauses
As much as I think checked exceptions are a mistake in Java, it is not hard to make up your mind about rethrows and apply them in a checked or unchecked form with little or no thought.

The unhappy path that you get for free with exceptions is correct for code with ordinary control flow. Most of the code has no global view of the application and is no position to handle errors. On the other hand, for many simple programs, the correct behavior is "abort the program, clean up resources, display an error message" which a sane exception system gives you for free (except for the finally which cleans up the happy path too)

For a complex control flow there is something high up in the call stack that has global responsibility. Imagine a webcrawler which is coordinating multiple threads that call fetchUrl(url) fetchUrl doesn't need to catch exceptions at all, just clean up with finally. What it may need to do is tag exceptions with contextual information that will help the coordinator make decisions. That webcrawler in particular will deal with intermittent failures all the time and only the coordinator is in a position to decide if it wants to retry and on one schedule.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: