Java Reference
In-Depth Information
//
// Assume that the source file's extension is RM (for
Real Media) and
// that the file's internal signature suggests that
its format is
// Microsoft WAVE.
String expectedFormat = "RM";
String existingFormat = "WAVE";
throw new InvalidMediaFormatExcep-
tion(expectedFormat, existingFormat);
}
}
Listing3-25 declaresthe Media classtobe final becausethisclasswillonlycon-
sist of class methods and there's no reason to extend it.
Media 's convert() method appends throws InvalidMediaFormatEx-
ception, IOException to its header. A throws clause identifies all checked ex-
ceptionsthatarethrownoutofthemethod,andwhichmustbehandledbysomeother
method. It consists of reserved word throws followed by a comma-separated list of
checkedexceptionclassnames,andisalwaysappendedtoamethodheader.The con-
vert() method's throws clause indicates that this method is capable of throwing an
InvalidMediaFormatException or IOException instance to the JVM.
convert() alsodemonstratesthethrowstatement,whichconsistsofreservedword
throw followedbyaninstanceof Throwable orasubclass.(Youtypicallyinstantiate
an Exception subclass.)ThisstatementthrowstheinstancetotheJVM,whichthen
searches for a suitable handler to handle the exception.
The first use of the throw statement is to throw a
java.lang.NullPointerException instancewhenanullreferenceispassedas
the source or destination filename. This unchecked exception is commonly thrown to
indicatethatacontracthasbeenviolatedviaapassednullreference.( Chapter6 ' sdiscus-
sion of the java.util.Objects class presents an alternative approach to dealing
withnullreferencespassedtoparameters.)Forexample,youcannotpassnullfilenames
to convert() .
The second use of the throw statement is to throw a me-
dia.InvalidMediaFormatException instance when the expected media
Search WWH ::




Custom Search