Java Reference
In-Depth Information
When and When Not to Use Exceptions
Because throwing, catching, and declaring exceptions are related concepts and can be
confusing, here's a quick summary of when to do what.
When to Use Exceptions
You can do one of three things if your method calls another method that has a throws
clause:
Deal with the exception by using try and catch statements.
n
Pass the exception up the calling chain by adding your own throws clause to your
method definition.
n
Perform both of the preceding methods by catching the exception using catch and
then explicitly rethrowing it using throw .
n
In cases where a method throws more than one exception, you can handle each of those
exceptions differently. For example, you might catch some of those exceptions while
allowing others to pass up the calling chain.
If your method throws its own exceptions, you should declare that it throws those meth-
ods using the throws statement. If your method overrides a superclass method that has a
throws statement, you can throw the same types of exceptions or subclasses of those
exceptions; you cannot throw any different types of exceptions.
Finally, if your method has been declared with a throws clause, don't forget to actually
throw the exception in the body of your method using the throw statement.
When Not to Use Exceptions
Although they might seem appropriate at the time, there are several cases in which you
should not use exceptions.
First, you should not use exceptions for circumstances you expect and could avoid easily.
For example, although you can rely on an ArrayIndexOutofBounds exception to indicate
when you've gone past the end of an array, it's easy to use the array's length variable to
prevent you from going beyond the bounds.
In addition, if your users will enter data that must be an integer, testing to make sure that
the data is an integer is a much better idea than throwing an exception and dealing with it
somewhere else.
 
Search WWH ::




Custom Search