Java Reference
In-Depth Information
A Simple Exception Example
Here is a simple example that illustrates how to watch for and catch an exception. As you
know, it is an error to attempt to index an array beyond its boundaries. When this oc-
curs, the JVM throws an ArrayIndexOutOfBoundsException . The following program
purposely generates such an exception and then catches it:
This program displays the following output:
Although quite short, the preceding program illustrates several key points about excep-
tion handling. First, the code that you want to monitor for errors is contained within a try
block. Second, when an exception occurs (in this case, because of the attempt to index
nums beyond its bounds), the exception is thrown out of the try block and caught by the
catch statement. At this point, control passes to the catch , and the try block is termin-
ated. That is, catch is not called. Rather, program execution is transferred to it. Thus, the
println( ) statement following the out-of-bounds index will never execute. After the catch
statement executes, program control continues with the statements following the catch .
Thus, it is the job of your exception handler to remedy the problem that caused the excep-
tion so that program execution can continue normally.
Search WWH ::




Custom Search