Java Reference
In-Depth Information
38
return
radius;
39 }
40
41
/** Set a new radius */
42
public void
setRadius(
double
newRadius)
43
throws
InvalidRadiusException {
44
if
(newRadius >=
0
)
45 radius = newRadius;
46
else
47
throw new
InvalidRadiusException(newRadius);
throw exception
48 }
49
50
/** 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: 1
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 43).
Since the constructors 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)
(line 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
12.25
How do you define a custom exception class?
12.26
Suppose the
setRadius
method throws the
InValidRadiusException
defined in
Listing 12.10. What is displayed when the following program is run?
✓
✓
Check
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"
);
}
Search WWH ::
Custom Search