Java Reference
In-Depth Information
Exceptions take up a lot of processing time for your Java program. A simple test or
series of tests will run much faster than exception handling and make your program more
efficient. Exceptions should be used only for truly exceptional cases that are out of your
control.
It's also easy to get carried away with exceptions and to try to make sure that all your
methods have been declared to throw all the possible exceptions that they can possibly
throw. This makes your code more complex; in addition, if other people will be using
your code, they'll have to deal with handling all the exceptions that your methods might
throw.
You're making more work for everyone involved when you get carried away with excep-
tions. Declaring a method to throw either few or many exceptions is a trade-off; the more
exceptions your method can throw, the more complex that method is to use. Declare only
the exceptions that have a reasonably fair chance of happening and that make sense for
the overall design of your classes.
Bad Style Using Exceptions
When you first start using exceptions, it might be appealing to work around the compiler
errors that result when you use a method that declares a throws statement. Although it is
legal to add an empty catch clause or to add a throws statement to your own method
(and there are appropriate reasons for doing so), intentionally dropping exceptions with-
out dealing with them subverts the checks that the Java compiler does for you.
The Java exception system was designed so that if an error can occur, you're warned
about it. Ignoring those warnings and working around them makes it possible for fatal
errors to occur in your program—errors that you could have avoided with a few lines of
code. Even worse, adding throws clauses to your methods to avoid exceptions means
that the users of your methods (objects further up in the calling chain) will have to deal
with them. You've just made your methods more difficult to use.
Compiler errors regarding exceptions are there to remind you to reflect on these issues.
Take the time to deal with the exceptions that might affect your code. This extra care
richly rewards you as you reuse your classes in later projects and in larger and larger pro-
grams. Of course, the Java class library has been written with exactly this degree of care,
and that's one of the reasons it's robust enough to be used in constructing all your Java
projects.
7
Search WWH ::




Custom Search