Java Reference
In-Depth Information
First we turn the data set name into a file name. Then we try to open
the file and read the data using the method readDataSet . If all goes well,
readDataSet will return an array of doubles, which we will return to the in-
voking code. If opening or reading the file causes an I/O exception, the
catch clause is executed. The catch clause creates a new BadDataSetEx-
ception object and throws it, in effect translating the I/O exception into
an exception specific to getdataSet . Methods that invoke geTDataSet can
catch the new exception and react to it appropriately. In either casere-
turning successfully with the data set or catching and then throwing an
exceptionthe code in the finally clause is executed to close the file if it
was opened successfully. If an exception occurs during close , we catch
it but ignore itthe semicolon by itself forms an empty statement, which
does nothing. Ignoring exceptions is not a good idea in general, but in
this case it occurs either after the data set is successfully readin which
case the method has fulfilled its contractor the method is already in the
process of throwing an exception. If a problem with the file persists, it
will be reported as an exception the next time we try to use it and can
be more appropriately dealt with at that time.
You will use finally clauses for cleanup code that must always be ex-
ecuted. You can even have a try - finally statement with no catch clauses
to ensure that cleanup code will be executed even if uncaught excep-
tions are thrown.
If a method's execution can result in checked exceptions being thrown,
it must declare the types of these exceptions in a throws clause, as
shown for the getdataSet method. A method can throw only those
checked exceptions it declaresthis is why they are called checked excep-
tions. It may throw those exceptions directly with tHRow or indirectly by
invoking a method that throws exceptions. Exceptions of type RuntimeEx-
ception , Error , or subclasses of these exception types are unchecked ex-
ceptions and can be thrown anywhere, without being declared.
Checked exceptions represent conditions that, although exceptional, can
reasonably be expected to occur, and if they do occur must be dealt
with in some waysuch as the IOException that may occur reading a file.
Declaring the checked exceptions that a method throws allows the com-
piler to ensure that the method throws only those checked exceptions
 
Search WWH ::




Custom Search