ptg7068951
250 HOUR 18:Handling Errors in a Program
For example, a common programming mistake is to refer to an element of
an array that doesn’t exist, as in the following statements:
String[] greek = { “Alpha”, “Beta”, “Gamma”};
System.out.println(greek[3]);
The Stringarray greekhas three elements. Because the first element of an
array is numbered 0 rather than 1, the first element is greek[0], the second
greek[1], and the third greek[2]. So the statement attempting to display
greek[3]is erroneous. The preceding statements compile successfully, but
when you run the program, the Java interpreter halts with a message such
as the following:
Output▼
Exception in thread “main” java.lang.ArrayIndexOutBoundsException: 3
at SampleProgram.main(SampleProgram.java:4)
This message indicates that the application has generated an exception,
which the interpreter noted by displaying an error message and stopping
the program.
The error message refers to a class called ArrayIndexOutOfBoundsException
in the java.langpackage. This class is an exception, an object that represents
an exceptional circumstance that has taken place in a Java program.
When a Java class encounters an exception, it alerts users of the class to the
error. In this example, the user of the class is the Java interpreter.
All exceptions are subclasses of Exceptionin the java.langpackage. The
ArrayIndexOutOfBoundsExceptiondoes what you would expect—it reports
that an array element has been accessed outside the array’s boundaries.
There are hundreds of exceptions in Java. Many such as the array excep-
tion indicate a problem that can be fixed with a programming change.
These are comparable to compiler errors—after you correct the situation,
you don’t have to concern yourself with the exception any longer.
Other exceptions must be dealt with every time a program runs by using
five new keywords: try, catch, finally, throw, and throws.
Catching Exceptions in a try-catchBlock
Up to this point, you have dealt with exceptions by fixing the problem that
caused them. There are times you can’t deal with an exception in that man-
ner and must handle the issue within a Java class.
NOTE
Tw o t e r m s a r e u s e d t o d e s c r i b e
this process: throwandcatch.
Objects throw exceptions to
alert others that they have
occurred. These exceptions are
caught by other objects or the
Java interpreter.