Java Reference
In-Depth Information
14.1 Introduction
Exception handling enables a program to deal with exceptional situations and
continue its normal execution.
Key
Point
Runtime errors occur while a program is running if the JVM detects an operation that is
impossible to carry out. For example, if you access an array using an index that is out of
bounds, you will get a runtime error with an ArrayIndexOutOfBoundsException . If you
enter a double value when your program expects an integer, you will get a runtime error with
an InputMismatchException .
In Java, runtime errors are thrown as exceptions. An exception is an object that represents
an error or a condition that prevents execution from proceeding normally. If the exception is
not handled, the program will terminate abnormally. How can you handle the exception so
that the program can continue to run or else terminate gracefully? This chapter introduces this
subject and text input and output.
exception
14.2 Exception-Handling Overview
Exceptions are thrown from a method. The caller of the method can catch and handle
the exception.
Key
Point
To demonstrate exception handling, including how an exception object is created and thrown,
let's begin with the example in Listing 14.1, which reads in two integers and displays their
quotient.
VideoNote
Exception-handling
advantages
L ISTING 14.1 Quotient.java
1 import java.util.Scanner;
2
3 public class Quotient {
4 public static void main(String[] args) {
5 Scanner input = new Scanner(System.in);
6
7 // Prompt the user to enter two integers
8 System.out.print( "Enter two integers: " );
9
int number1 = input.nextInt();
reads two integers
10
int number2 = input.nextInt();
11
12 System.out.println(number1 + " / " + number2 + " is " +
13 (
number1 / number2
));
integer division
14 }
15 }
5 2
Enter two integers:
5 / 2 is 2
Enter two integers:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Quotient.main(Quotient.java:11)
3 0
If you entered 0 for the second number, a runtime error would occur, because you cannot
divide an integer by 0 . ( Recall that a floating-point number divided by 0 does not raise an
exception. ) A simple way to fix this error is to add an if statement to test the second number,
as shown in Listing 14.2.
 
 
 
Search WWH ::




Custom Search