Java Reference
In-Depth Information
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.4, 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 Using a Programmer-Defined Exception Class (part 1 of 3)
1
import java.util.Scanner;
We will present an improved version of
this program later in this chapter.
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();
13
if (denominator == 0)
14
throw new DivisionByZeroException();
15
double quotient = numerator/( double )denominator;
16
System.out.println(numerator + "/"
17
+ denominator
18
+ " = " + quotient);
19
}
20
catch (DivisionByZeroException e)
21
{
22
System.out.println(e.getMessage());
23
secondChance();
24
}
25
System.out.println("End of program.");
26
}
27
public static void secondChance()
28
{
29
Scanner keyboard = new Scanner(System.in);
Search WWH ::




Custom Search