Java Reference
In-Depth Information
The File Input/Output section in Chapter 3 defined an exception as an occurrence of an
undesirable situation that can be detected during program execution. For example,
division by zero and inputting invalid data are exceptions. Similarly, trying to open an
input file that does not exist is an exception, as is an array index that is outside the bounds
of the array.
Until now, our programs have not included any code to handle exceptions. If exceptions
occurred during program execution, the program terminated with an appropriate error
message. However, there are situations when an exception occurs and you don't want the
program to simply ignore the exception and terminate. For example, a program that
monitors stock performance should not automatically sell if the value of the stock exceeds
a certain threshold. It should inform the stockholder and request an appropriate action.
This chapter provides more detail about exceptions and describes how they are handled
in Java. You will learn about different kinds of exceptions and the options available to
programmers for dealing with them. You'll also extend what you learned in Chapters 6
and 10 about event handling.
Handling Exceptions Within a Program
Chapter 2 stated that if you try to input incompatible data into a variable, the program
will terminate with an error message indicating that an exception has occurred. For
example, inputting a letter or number containing a nondigit character into an int
variable would cause an exception to occur. Before we discuss how to handle exceptions,
let us give some examples that show what can happen if an exception is not handled.
The program in Example 11-1 shows what happens when division by zero is attempted
or an invalid input occurs and the problem is not addressed.
EXAMPLE 11-1
import java.util.*;
public class ExceptionExample1
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int dividend, divisor, quotient;
//Line 1
System.out.print("Line 2: Enter the "
+ "dividend: ");
//Line 2
dividend = console.nextInt();
//Line 3
System.out.println();
//Line 4
 
Search WWH ::




Custom Search