Java Reference
In-Depth Information
format does not match the existing format. In the contrived example, the exception is
thrown because the expected format is RM and the existing format is WAVE.
Unlike InvalidMediaFormatException , NullPointerException isnot
listedin convert() 'sthrowsclausebecause NullPointerException instances
areunchecked.Theycanoccursofrequentlythatitistoobigaburdentoforcethedeve-
lopertoproperlyhandletheseexceptions.Instead,thedevelopershouldwritecodethat
minimizes their occurrences.
Although not thrown from convert() , IOException is listed in this method's
throwsclauseinpreparationforrefactoringthismethodtoperformtheconversionwith
the help of file-handling code.
NullPointerException isonekindofexceptionthatisthrownwhenanargu-
mentprovestobeinvalid.The java.lang.IllegalArgumentException class
generalizestheillegalargumentscenariotoincludeotherkindsofillegalarguments.For
example,thefollowingmethodthrowsan IllegalArgumentException instance
when a numeric argument is negative:
public static double sqrt(double x)
{
if (x < 0)
throw new IllegalArgumentException(x+" is negative");
// Calculate the square root of x.
}
Thereareafewadditionalitemstokeepinmindwhenworkingwiththrowsclauses
and throw statements:
• Youcanappendathrowsclausetoaconstructorandthrowanexceptionfrom
theconstructorwhensomethinggoeswrongwhiletheconstructorisexecuting.
The resulting object will not be created.
• Whenanexceptionisthrownoutofanapplication's main() method,theJVM
terminates the application and calls the exception's printStackTrace()
method to print, to the console, the sequence of nested method calls that was
awaiting completion when the exception was thrown.
• Ifasuperclassmethoddeclaresathrowsclause,theoverridingsubclassmethod
doesnothavetodeclareathrowsclause.However,ifthesubclassmethoddoes
declareathrowsclause,theclausemustnotincludethenamesofcheckedex-
ception classes that are not also included in the superclass method's throws
clause, unless they are the names of exception subclasses. For example, given
superclass method void foo() throws IOException {} , the over-
Search WWH ::




Custom Search