Java Reference
In-Depth Information
TIP: An Exception Class Can Carry a Message of Any Type
It is possible to define your exception classes so they have constructors that take
arguments of other types that are stored in instance variables. In such cases, you
would define accessor methods for the value stored in the instance variable. For
example, if that is desired, you can have an exception class that carries an
int
as a
message. In that case, you would need a new accessor method name, perhaps
getBadNumber()
. An example of one such exception class is given in Display 9.5.
Display 9.6 is a demonstration of how to use the accessor method
getBadNumber()
.
This is just a toy program, but it does illustrate the details of how an exception
object can carry a numeric message.
■
Display 9.5
An Exception Class with an
int
Message
1
public
class
BadNumberException
extends
Exception
2{
3
private int
badNumber;
4
public
BadNumberException(
int
number)
5
{
6
super
("BadNumberException");
7
badNumber = number;
8
}
9
public
BadNumberException()
10
{
11
super
("BadNumberException");
12
}
13
public
BadNumberException(String message)
14
{
15
super
(message);
16
}
17
public int
getBadNumber()
18
{
19
return
badNumber;
20
}
21
}