The Artima Developer Community
Sponsored Link

Where to catch exceptions

Advertisement

Advertisement

This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Where to catch exceptions

Posted by Bill Venners on 22 Jun 1998, 2:28 PM

One reader submitted a comment that I thought others might
find useful.

This read said said it took him about a year to
actually "learn how to live with exceptions." He said
that at first he thought he should catch exceptions as close
as possible to where they were thrown so he could "keep
control of them." Eventually, he said, he started to realize
that by default you want to pass Exceptions upstream. That is,
put your whole main() method in a try/catch block, and always
throw exceptions as high up as possible unless there is
a reason to catch them. He said that this makes coping with
exceptions less burdensome.

My own thought is that one should catch exceptions in the
method that knows how to handle that exception, and that is
usually going to be at the application level. Exceptions let
you transfer control from the part of a program where an
error or problem is detected to another part of the program
that knows how to handle the error.

For example, a low-level read method may have trouble reading
in the next byte of data, but that read-method is in a
library that could be used by lots of applications. One
application may want to retry, another may want to abort,
another may want to put up a dialog box, and so on. The low-
level read method has no idea what the app wants to do, so
it throws an exception instead of handling the error.

So generally you'll want to catch and handle exceptions in
the "application" part of your program. From libraries that
are (or potentially may be eventually) shared by multiple
applications will often throw exceptions and not handle
them.

bv



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us