Java Reference
In-Depth Information
of Error or RuntimeException is called a checked exception . A method m (say)
that possibly throws a checked exception is syntactically illegal unless m either
catches it or mentions it in a throws-clause in the method header —in which case
any method that calls m is viewed also as throwing the checked exception.
Self-review exercises
SR1. If execution of a try-block does not throw an exception, what happens
when execution of the try-block finishes?
SR2. What happens if several catch-clauses can catch an object that is thrown in
a try-block?
SR3. If a thrown exception is not handled by a method, what happens to it?
SR4. What message do you get if you reference obj.x and obj contains null ?
What does it mean?
SR5. What kinds of exceptions have to be declared with a throws-clause? What
are such exceptions called?
SR6. Does throwing an Exception have to cause abortion of the program? What
about throwing an Error ?
SR7. When is it mandatory to have at least one catch-clause in a try-statement?
SR8. Write a catch-clause that will catch all thrown exceptions (but not Errors ).
SR9. Can a throwable object be thrown in a catch-block?
SR10. Can a catch-block throw the object that it caught? If so, why would one
want to do this?
Exercises for Chapter 10
E1. Write a procedure to print the real roots of the quadratic formula ax 2 +bx+
c . These are the values (-b + sqrt(b 2 - 4ac))/2a and (-b - sqrt(b 2 -
4ac))/2a , and they are real if (and only if) the discriminant b 2 - 4ac is non-
negative. If the discriminant is negative, something drastic must be done. Be sure
to specify your procedure. Now, this procedure should be written in two ways:
(1) throw an exception if the discriminant is real and (2) do not use exceptions at
all but print an error message. Which way is better?
E2. Write a function to return the real root (-b + sqrt(b 2 - 4ac))/2a of the
quadratic formula ax 2 +bx+c (see the previous exercise). If the discriminant is
negative, the function should throw an IllegalArgumentException . Be sure to
write a good specification of the function, and be sure to test the function thor-
Search WWH ::

Custom Search