Java Reference
In-Depth Information
PITFALL: (continued)
catch
(NegativeNumberException e)
{
.
.
.
}
With this ordering, the
catch
block for
NegativeNumberException
would
never be used, because all exceptions are caught by the first
catch
block.
Fortunately, the compiler will warn you about this. The correct ordering is to
reverse the
catch
blocks so that the more specific exception comes before its
parent exception class, as shown in the following:
The second
catch
block can
never be reached.
catch
(NegativeNumberException e)
{
.
.
.
}
catch
(Exception e)
{
.
.
.
}
■
Display 9.9
The Class
NegativeNumberException
1
public class
NegativeNumberException
extends
Exception
2 {
3
public
NegativeNumberException()
4 {
5
super
("Negative Number Exception!");
6 }
7
public
NegativeNumberException(String message)
8 {
9
super
(message);
10 }
11 }