Java Reference
In-Depth Information
This example code is prepared to handle one of the exceptions
re-
placeValue
throws:
Object value = new Integer(8);
try {
attributedObj.replaceValue("Age", value);
} catch (NoSuchAttributeException e) {
// shouldn't happen, but recover if it does
Attr attr = new Attr(e.attrName, value);
attributedObj.add(attr);
}
The
try
sets up a statement (which must be a block) that does
something that is normally expected to succeed. If everything succeeds,
the block is finished. If any exception is thrown during execution of the
code in the
try
block, either directly via a
throw
or indirectly by a meth-
od invoked inside it, execution of the code inside the
try
stops, and the
attached
catch
clause is examined to see whether it wants to catch the
exception that was thrown.
A
catch
clause is somewhat like an embedded method that has one para-
meter namely, the exception to be caught. As with method parameters,
the exception "parameter" can be declared
final
, or can have annota-
tions applied. Inside a
catch
clause, you can attempt to recover from the
exception, or you can clean up and rethrow the exception so that any
code calling yours also has a chance to catch it. Or a
catch
can do what it
needs to and then fall out the bottom, in which case control flows to the
statement after the
try
statement (after executing the
finally
clause, if
there is one).
A general
catch
clauseone that catches exceptions of type
Exception
, for
exampleis usually a poor implementation choice since it will catch
any
exception, not just the specific one you are interested in. Had we used
such a clause in our code, it could have ended up handling, for example,
a
ClassCastException
as if it were a missing attribute problem.