Re: What's On Your Java SE 7 Wish List?
Posted: Dec 29, 2006 1:51 PM
> > Is that because checked exceptions are bad or because
> > Exception hierarchies are poorly designed and error
> > handling code is almost always a poorly crafted
> > afterthought?
> That's not an either or question.
> Checked exceptions are bad - period.
Well, I'm not convinced that they are inherently bad, just that they have been poorly applied.
> Both your exception handling code and your exception
> hierarchies should be centered around the one central
> What is my failure strategy?
Yes, but it depends on the type of failure. A program can "fail" because it contains flaws in its logic, because something out of its control has changed in its environment, because it was setup improperly, or simply because it received bad input from the user.
> For most applications, fail-fast is probably the best
> choice. Fail-fast means that you don't try to recover from
> exceptions, you just report them - so that the bug can be
What if it's not a bug but rather user input? Configuration done by an administrator? A transient unexpected state, such as a database being down?
> You only ever catch exceptions (I'm not talking
> about try-finally), in one of the following situations
> 1) you are calling a legacy method (which declares checked
> 2) you want to add context (such as line number of a
> parsed file) to an exception. In that case, you catch
Exception, not a subclass, such as
> If your application needs to work even in the presece of
> errors, you need to catch exceptions in one (or a few)
> central place(s) per thread. In those places, you can
> retry an operation or roll back to some save point that
> you created earlier.
> In this scenario, it is important that you do not try to
> deal with the errors in other places (it will only prevent
> the save point from being restored). Here, again, checked
> exceptions get in your way.
Ahh yes, if an exception is thrown because user input caused a constaint to be violated in the database, two things need to happen:
1) The transaction needs to be rolled back and any resources cleaned up - and I agree that a centrally managed strategy is best for this (when possible)
2) The user needs to be informed what is wrong and how to fix it
What you are advocating achieves #1 and fails on #2. That's fine for errors that are beyond the user's control, but it's bad for ones that are under the user's control.
Transaction rollback, resource cleanup, etc. should be more orthogonal to the main application logic and really should be done as the stack unwinds, preferably using an RAII type pattern or under today's Java reality with try/finally.