Java Reference
In-Depth Information
implement a BadData-Exception . Which exception class should
you extend?
Q UALITY T IP 11.4
Do Throw Specific Exceptions
When throwing an exception, you should choose an exception class that describes
the situation as closely as possible. For example, it would be a bad idea to simply
throw a Runtime-Exception object when a bank account has insufficient
funds. This would make it far too difficult to catch the exception. After all, if you
caught all exceptions of type Runtime-Exception , your catch clause would
also be activated by exceptions of the type NullPointer-Exception ,
ArrayIndexOutOfBoundsException , and so on. You would then need to
carefully examine the exception object and attempt to deduce whether the
exception was caused by insufficient funds.
514
515
If the standard library does not have an exception class that describes your
particular error situation, simply define a new exception class.
11.7 Case Study: A Complete Example
This section walks through a complete example of a program with exception
handling. The program asks a user for the name of a file. The file is expected to
contain data values. The first line of the file contains the total number of values, and
the remaining lines contain the data. A typical input file looks like this:
3
1.45
-2.1
0.05
What can go wrong? There are two principal risks.
ȗ
The file might not exist.
ȗ
The file might have data in the wrong format.
Who can detect these faults? The FileReader constructor will throw an exception
when the file does not exist. The methods that process the input values need to throw
an exception when they find an error in the data format.
Search WWH ::




Custom Search