Java Reference
In-Depth Information
riding subclass method could be declared as void foo() {} , void
foo() throws IOException {} , or void foo() throws
FileNotFoundException —the
java.io.FileNotFoundException class subclasses IOException .
• A checked exception class name does not need to appear in a throws clause
when the name of its superclass appears.
• Thecompilerreportsanerrorwhenamethodthrowsacheckedexceptionand
does not also handle the exception or list the exception in its throws clause.
• Do not include the names of unchecked exception classes in a throws clause.
Thesenamesarenotrequiredbecausesuchexceptionsshouldeveroccur.Fur-
thermore,theyonlycluttersourcecode,andpossiblyconfusesomeonewhois
trying to understand that code.
• You can declare a checked exception class name in a method's throws clause
withoutthrowinganinstanceofthisclassfromthemethod.(Perhapsthemethod
has yet to be fully coded.) However, Java requires that you provide code to
handle this exception, even though it is not thrown.
Handling Exceptions
A method indicates its intention to handle one or more exceptions by specifying a try
statementthatincludesoneormoreappropriatecatchblocks.Thetrystatementconsists
ofreservedword try followedbyabrace-delimitedbody.Youplacecodethatthrows
exceptions into this block.
Acatchblockconsistsofreservedword catch ,followedbyaroundbracket-delim-
itedsingle-parameterlistthatspecifiesanexceptionclassname,followedbyabrace-de-
limitedbody.Youplacecodethathandlesexceptionswhosetypesmatchthetypeofthe
catch block's parameter list's exception class parameter in this block.
Acatchblockisspecifiedimmediatelyafteratryblock.Whenanexceptionisthrown,
the JVM searches for a handler by first examining the catch block to see whether its
parameter type matches or is the superclass type of the exception that has been thrown.
Ifthecatchblockisfound,itsbodyexecutesandtheexceptionishandled.Otherwise,
theJVMproceedsupthemethod-callstack,lookingforthefirstmethodwhosetrystate-
mentcontainsanappropriatecatchblock.Thisprocesscontinuesunlessacatchblockis
found or execution leaves the main() method.
The following example illustrates try and catch:
Search WWH ::




Custom Search