Java Reference
In-Depth Information
Self-Test Exercises
30. How would the dialogue in Display 9.11 change if you were to omit the following
line from the
catch
block? (Try it and see.)
keyboard.nextLine();
31. Give the definition for the following method. Use the techniques given in Display
9.11.
/**
Precondition: keyboard is an object of the class Scanner that
has been set up for keyboard input (as we have been doing
right along). Returns: An int value entered at the keyboard.
If the user enters an incorrectly formed input she or he is
prompted to reenter the value,
*/
public static int
getInt(Scanner keyboard)
ArrayIndexOutOfBoundsException
You should read Section 6.1 of Chapter 6, which covers array basics, before reading
this short subsection. If you have not yet covered some of Chapter 6, you can omit this
section and return to it at a later time.
If your program attempts to use an array index that is out of bounds, an
Array-
IndexOutOfBoundsException
is thrown and your program ends, unless the exception
is caught in a
catch
block.
ArrayIndexOutOfBoundsException
is a descendent of the
class
RuntimeException
and so need not be caught or accounted for in a
throws
clause. This sort of exception normally indicates that there is something wrong with
your code and means that you need to fix your code, not catch an exception. Thus, an
ArrayIndexOutOfBoundsException
normally functions more like a run-time error
message than a regular exception.
ArrayIndexOutOfBoundsException
is in the standard Java package
java.lang
and
so requires no import statement should you decide to use it by name.
Chapter Summary
•
Exception handling allows you to design and code the normal case for your pro-
gram separately from the code that handles exceptional situations.
•
An exception can be thrown in a
try
block. Alternatively, an exception can be
thrown in a method definition that does not include a
try
block (or does not
include a
catch
block to catch that type of exception). In this case, an invocation
of the method can be placed in a
try
block.