Deitel & Associates, Inc. Logo

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

© 2005
pages: 1576
Buy the Book!
Amazon logo
InformIT logo

An exception is an indication of a problem that occurs during a program's execution. The name "exception" implies that the problem occurs infrequently-if the "rule" is that a statement normally executes correctly, then the "exception to the rule" is that a problem occurs. Exception handling enables programmers to create applications that can resolve (or handle) exceptions. In many cases, handling an exception allows a program to continue executing as if no problem had been encountered. A more severe problem could prevent a program from continuing normal execution, instead requiring it to notify the user of the problem before terminating in a controlled manner. Exception handling enables programmers to write robust and fault-tolerant programs (i.e., programs that are able to deal with problems that may arise and continue executing). This tutorial demonstrates a program in which a exceptions occur. The program does not process these exceptions, which results in difficult-to-understand error messages being displayed to the user. In Part 2 of this tutorial, we demonstrate how to catch and handle these exceptions. 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.3) 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.641-643. Electronically reproduced by permission of Pearson Education, Inc., Upper Saddle River, New Jersey.]

13.3 Divide By Zero Without Exception Handling

First we demonstrate what happens when errors arise in an application that does not use exception handling. Figure Fig. 13.1 prompts the user for two integers and passes them to method quotient, which calculates the quotient and returns an int result. In this example, we will see that exceptions are thrown (i.e., the exception occurs) when a method detects a problem and is unable to handle it.

Fig. 13.1 Integer division without exception handling.
   1  // Fig. 13.1:
2 // An application that attempts to divide by zero.
3 import java.util.Scanner;
5 public class DivideByZeroNoExceptionHandling
6 {
7 // demonstrates throwing an exception when a divide-by-zero occurs
8 public static int quotient( int numerator, int denominator )
9 {
10 return numerator / denominator; // possible division by zero
11 } // end method quotient
13 public static void main( String args[] )
14 {
15 Scanner scanner = new Scanner( ); // scanner for input
17 System.out.print( "Please enter an integer numerator: " );
18 int numerator = scanner.nextInt();
19 System.out.print( "Please enter an integer denominator: " );
20 int denominator = scanner.nextInt();
22 int result = quotient( numerator, denominator );
23 System.out.printf(
24 "\nResult: %d / %d = %d\n", numerator, denominator, result );
25 } // end main
26 } // end class DivideByZeroNoExceptionHandling
Please enter an integer numerator: 100
Please enter an integer denominator: 7

Result: 100 / 7 = 14

Please enter an integer numerator: 100
Please enter an integer denominator: 0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at DivideByZeroNoExceptionHandling.quotient(
at DivideByZeroNoExceptionHandling.main(

Please enter an integer numerator: 100
Please enter an integer denominator: hello
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at DivideByZeroNoExceptionHandling.main(

The first of the three sample executions in Fig. Fig. 13.1 shows a successful division. In the second sample execution, the user enters the value 0 as the denominator. Notice that several lines of information are displayed in response to this invalid input. This information is known as the stack trace, which includes the name of the exception (java.lang.ArithmeticException) in a descriptive message that indicates the problem that occurred and the complete method-call stack (i.e., the call chain) at the time the exception occurred. The stack trace includes the path of execution that led to the exception method by method. This information helps in debugging a program. The first line specifies that an ArithmeticException has occurred. The text after the name of the exception, “/ by zero”, indicates that this exception occurred as a result of an attempt to divide by zero. Java does not allow division by zero in integer arithmetic. [Note: Java does allow division by zero with floating-point values. Such a calculation results in the value infinity, which is represented in Java as a floating-point value (but actually displays as the string Infinity).] When division by zero in integer arithmetic occurs, Java throws an ArithmeticException. ArithmeticExceptions can arise from a number of different problems in arithmetic, so the extra data (“/ by zero”) gives us more information about this specific exception.

Starting from the last line of the stack trace, we see that the exception was detected in line 22 of method main. Each line of the stack trace contains the class name and method (DivideByZeroNoExceptionHandling.main) followed by the file name and line number ( Moving up the stack trace, we see that the exception occurs in line 10, in method quotient. The top row of the call chain indicates the throw point—the initial point at which the exception occurs. The throw point of this exception is in line 10 of method quotient.

In the third execution, the user enters the string "hello" as the denominator. Notice again that a stack trace is displayed. This informs us that an InputMismatchException has occurred (package java.util). Our prior examples that read numeric values from the user assumed that the user would input a proper integer value. However, users sometimes make mistakes and input noninteger values. An InputMismatchException occurs when Scanner method nextInt receives a string that does not represent a valid integer. Starting from the end of the stack trace, we see that the exception was detected in line 20 of method main. Moving up the stack trace, we see that the exception occurs in method nextInt. Notice that in place of the file name and line number, we are provided with the text Unknown Source. This means that the JVM does not have access to the source code for where the exception occurred.

Notice that in the sample executions of Fig. Fig. 13.1 when exceptions occur and stack traces are displayed, the program also exits. This does not always occur in Java—sometimes a program may continue even though an exception has occurred and a stack trace has been printed. In such cases, the application may produce unexpected results. The next section demonstrates how to handle these exceptions and keep the program running successfully.

In Fig. Fig. 13.1 both types of exceptions were detected in method main. In the next example, we will see how to handle these exceptions to enable the program to run to normal completion.