Java Reference
In-Depth Information
of a String instance variable that can later be recovered with a call to getMessage .
The method getMessage is an ordinary accessor method of the class Exception . The
class DivisionByZeroException inherits this String instance variable as well as the
accessor method getMessage .
For example, in Display 9.5, we give a sample program that uses this exception class.
The exception is thrown using the no-argument constructor, as follows:
throw new DivisionByZeroException();
Display 9.4
A Programmer-Dei ned Exception Class
1 public class DivisionByZeroException extends Exception
2 {
3 public DivisionByZeroException()
4 {
5
You can do more in an exception
constructor, but this form is
common.
super ("Division by Zero!");
6 }
7 public DivisionByZeroException(String message)
8 {
9
super is an invocation of the constructor
for the base class Exception .
super (message);
10 }
11 }
Display 9.5
Using a Programmer-Dei ned Exception Class (part 1 of 3)
1 import java.util.Scanner;
We will present an improved version of this
program later in this chapter in Display 9.10.
2 public class DivisionDemoFirstVersion
3 {
4 public static void main(String[] args)
5 {
6 try
7 {
8 Scanner keyboard = new Scanner(System.in);
9 System.out.println("Enter numerator:");
10 int numerator = keyboard.nextInt();
11 System.out.println("Enter denominator:");
12
int denominator = keyboard.nextInt();
(continued)
 
 
Search WWH ::




Custom Search