Deitel & Associates, Inc. Logo

Back to www.deitel.com
digg.png delicious.png blinkit.png furl.png
Java How to Program, 6/e

ISBN:
0-13-148398-6
© 2005
pages: 1576
Buy the Book!
Amazon logo
InformIT logo

In Part 1 of this tutorial we showed the premature termination of a program in which unhandled exceptions occur. In this tutorial, we demonstrate how to catch and handle these exceptions to enable the program to continue executing. This tutorial is intended for students and professionals who are familiar with classes and basic inheritance concepts in Java.

Download the code for this tutorial here.

[Note: This tutorial is an excerpt (Section 13.4) of Chapter 13, Exception Handling, from our textbook Java How to Program, 6/e. This tutorial may refer to other chapters or sections of the book that are not included here. Permission Information: Deitel, Harvey M. and Paul J., JAVA HOW TO PROGRAM, ©2005, pp.643-648. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

13.4 Handling ArithmeticExceptions and InputMismatchExceptions (Continued)

The first sample execution in Fig. Fig. 13.2 shows a successful execution that does not encounter any problems. In the second execution, the user enters a zero denominator and an ArithmeticException exception occurs. In the third execution, the user enters the string “hello” as the denominator, and an InputMismatchException occurs. For both exceptions, the user is informed of their mistake and asked to try again, then is prompted for two new integers. In each sample execution, the program runs successfully to completion. Class InputMismatchException is imported in line 3. Class ArithmeticException does not need to be imported because it is located in package java.lang. Method main (lines 15–49) creates a Scanner object at line 17. Line 18 creates the boolean variable continueLoop, which is true if the user has not yet entered valid input. Lines 20–48 contain a do...while statement that repeatedly asks users for input until a valid input is received. Enclosing Code in a try Block Lines 22–33 contain a try block, which encloses the code that might throw an exception and the code that should not execute if an exception occurs (i.e., if an exception occurs, the remaining code in the try block will be skipped). A try block consists of the keyword try followed by a block of code enclosed in curly braces ({}). [Note: The term “try block” sometimes refers only to the block of code that follows the try keyword (not including the try keyword itself). For simplicity, we use the term “try block” to refer to the block of code that follows the try keyword, as well as the try keyword.] The statements that read the integers from the keyboard (lines 25 and 27) each use method nextInt to read an int value. Method nextInt throws an InputMismatchException if the value read in is not a valid integer. The division that can cause an ArithmeticException is not performed in the try block. Rather, the call to method quotient (line 29) invokes the code that attempts the division (line 12); the JVM throws an ArithmeticException object when the denominator is zero.
Software Engineering Observation
Software Engineering Observation 13.1
Exceptions may surface through explicitly mentioned code in a try block, through calls to other methods, through deeply nested method calls initiated by code in a try block or from the Java Virtual Machine as it executes Java bytecodes.
Software Engineering Observation
Software Engineering Observation 13.1
Exceptions may surface through explicitly mentioned code in a try block, through calls to other methods, through deeply nested method calls initiated by code in a try block or from the Java Virtual Machine as it executes Java bytecodes.
The try block in this example is followed by two catch blocks—one that handles an InputMismatchException (lines 34–41) and one that handles an ArithmeticException (lines 42–47). A catch block (also called a catch clause or exception handler) catches (i.e., receives) and handles an exception. A catch block begins with the keyword catch and is followed by a parameter in parentheses (called the exception parameter, discussed shortly) and a block of code enclosed in curly braces. [Note: The term “catch clause” is sometimes used to refer to the keyword catch followed by a block of code, where the term “catch block” refers to only the block of code following the catch keyword, but not including it. For simplicity, we use the term “catch block” to refer to the block of code following the catch keyword, as well as the keyword itself.] At least one catch block or a finally block (discussed in Section Section 13.7) must immediately follow the try block. Each catch block specifies in parentheses an exception parameter that identifies the exception type the handler can process. When an exception occurs in a try block, the catch block that executes is the one whose type matches the type of the exception that occurred (i.e., the type in the catch block matches the thrown exception type exactly or is a superclass of it). The exception parameter’s name enables the catch block to interact with a caught exception object—e.g., to implicitly invoke the caught exception’s toString method (as in lines 37 and 44), which displays basic information about the exception. Line 38 of the first catch block calls Scanner method nextLine. Because an InputMismatchException occurred, the call to method nextInt never successfully read in the user’s data—so we read that input with a call to method nextLine. We do not do anything with the input at this point, because we know that it is invalid. Each catch block displays an error message and asks the user to try again. After either catch block terminates, the user is prompted for input. We will soon take a deeper look at how this flow of control works in exception handling.
Common Programming Error
Common Programming Error 13.1
It is a syntax error to place code between a try block and its corresponding catch blocks.
Common Programming Error
Common Programming Error 13.2
Each catch block can have only a single parameter—specifying a comma-separated list of exception parameters is a syntax error.
Common Programming Error
Common Programming Error 13.3
It is a compilation error to catch the same type in two different catch blocks in a single try statement.
Common Programming Error
Common Programming Error 13.1
It is a syntax error to place code between a try block and its corresponding catch blocks.
Common Programming Error <
Common Programming Error 13.2
Each catch block can have only a single parameter—specifying a comma-separated list of exception parameters is a syntax error.
Common Programming Error
Common Programming Error 13.3
It is a compilation error to catch the same type in two different catch blocks in a single try statement.

An uncaught exception is an exception that occurs for which there are no matching catch blocks. You saw uncaught exceptions in the second and third outputs of Fig. Fig. 13.1. Recall that when exceptions occurred in that example, the application terminated early (after displaying the exception’s stack trace). This does not always occur as a result of uncaught exceptions. As you will learn in Chapter Chapter 23, Java uses a multithreaded model of program execution. Each thread is a parallel activity. One program can have many threads. If a program has only one thread, an uncaught exception will cause the program to terminate. If a program has multiple threads, an uncaught exception will terminate only the thread where the exception occurred. In such programs, however, certain threads may rely on others and if one thread terminates due to an uncaught exception, there may be adverse effects to the rest of the program.

Page 1 | 2 | 3 | 4
Related Tutorials :
Divide By Zero Without Exception Handling
Return to Tutorial Index

Google