Page 593 - Introduction to Programming with Java: A Problem Solving Approach
P. 593
After passing the exception object to the catch block, the JVM executes the catch block’s body. In this example, the catch block prints an “Invalid entry . . .” message and assigns a random number to the num variable. Then execution continues with the code below the catch block.
Throwing an Exception
When the JVM instantiates an exception object, we say that the JVM throws an exception. We’d prefer to say “throws an exception object” rather than “throws an exception” since the thing that’s being thrown is an exception object. But most programmers don’t worry about the difference between an exception, which is an event, and an exception object. No big deal. We’ll go with the flow and use the standard terminology— throwing an exception.
When the JVM throws an exception, the JVM looks for a matching catch block. If it finds a match-
ing catch block, it executes it. If it does not find a matching catch block, the JVM prints the excep-
tion object’s exception message and terminates the program. What is a “matching catch block”? A
catch block is “matching” if the catch heading’s parameter type is the same as the type of the thrown 2
exception. For example, in the LuckyNumber program, the InputMismatchException param- eter matches the InputMismatchException object thrown by the nextInt method call. So the InputMismatchException parameter’s catch block is a matching catch block if and when the nextInt method call throws an InputMismatchException.
An exception object contains information about the error, including the error’s type and a list of the method calls that led to the error. We’ll use some of the exception object’s information later on, but for now, all we need the exception object for is its ability to match up with the proper catch block.
Apago PDF Enhancer
14.4 Line Plot Example
Now let’s see how try and catch are used in the context of a more complicated program. We start by pre- senting a program without try and catch blocks. Then we analyze the program and determine how it can be improved by adding try and catch blocks.
First-Cut LinePlot Program
The program in Figure 14.2 plots a line by reading in coordinate positions for a series of points. The best way to get a handle on what the LinePlot program does is to show a sample session. Below, the user chooses to plot a line that goes from the origin (the default starting point) to point (3,1) to point (5,2):
Sample session:
Enter x & y coordinates (q to quit): 3 1
New segment = (0,0)-(3,1)
Enter x & y coordinates (q to quit): 5 2
New segment = (3,1)-(5,2)
Enter x & y coordinates (q to quit): q
2 Actually, as you’ll see in Section 14.9, a catch block is also considered matching if the catch heading’s parameter type is a superclass of the thrown exception’s class.
14.4 Line Plot Example 559