Java Reference
In-Depth Information
37
public double
getRadius() {
38
return
radius;
39 }
40
41
/** Set a new radius */
public void
setRadius(
double
newRadius)
42
43
throws
InvalidRadiusException
{
44
if
(newRadius >=
0
)
45 radius = newRadius;
46
else
47
48 }
49
50
throw new
InvalidRadiusException(newRadius);
/** Return numberOfObjects */
51
public static int
getNumberOfObjects() {
52
return
numberOfObjects;
53 }
54
55
/** Return the area of this circle */
56
public double
findArea() {
57
return
radius * radius *
3.14159
;
58 }
59 }
InvalidRadiusException: Invalid radius -5.0
Number of objects created: 0
The
setRadius
method in
CircleWithCustomException
throws an
InvalidRadius-
Exception
when radius is negative (line 47). Since
InvalidRadiusException
is a checked
exception, the
setRadius
method must declare it in the method header (line 42). Since the con-
structors for
CircleWithCustomException
invoke the
setRadius
method to a set a new
radius and it may throw an
InvalidRadiusException
, the constructors are declared to throw
InvalidRadiusException
(lines 25, 31).
Invoking
new CircleWithCustomException(-5)
throws an
InvalidRadius-
Exception
, which is caught by the handler. The handler displays the radius in the exception
object
ex
.
Tip
Can you define a custom exception class by extending
RuntimeException
? Yes, but
it is not a good way to go, because it makes your custom exception unchecked. It is bet-
ter to make a custom exception checked, so that the compiler can force these exceptions
to be caught in your program.
checked custom exception
14.24
✓
✓
How do you define a custom exception class?
Check
14.25
Suppose the
setRadius
method throws the
InValidRadiusException
defined in
Listing 14.10. What is displayed when the following program is run?
Point
public class
Test {
public static void
main(String[] args) {
try
{
method();
System.out.println(
"After the method call"
);
}
catch
(RuntimeException ex) {
System.out.println(
"RuntimeException in main"
);