© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
Outline
24.1 Test-Driving the Enhanced Car Payment Calculator Application 24.2 Introduction to Exception Handling
24.3 Exception Handling in Java 24.4 Java Exception Hierarchy
24.5 Constructing the Enhanced Car Payment Calculator Application 24.6 Wrap-Up
Tutorial 24 – Enhanced Car Payment Calculator Application
Introducing Exception Handling
Objectives
• In this tutorial, you will learn to:
– Understand exception handling
– Use the try block, the catch block, the finally block and the throws clause to handle exceptions.
– Understand the exception inheritance hierarchy.
– Distinguish checked and unchecked exceptions.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.1 Test-Driving the Enhanced Car Payment Calculator Application
Application Requirements
A bank wishes to prevent users from entering incorrect data on their car loans.
Although the application you developed in Tutorial 8 continues running when incorrect data is entered, it will not calculate the result. Alter the Car Payment Calculator application to allow users to enter only integers in the Price:
JTextField and Down payment: JTextField. If the user enters anything besides an integer (such as a double or any non-numeric data), a message should be displayed instructing the user to enter an integer. Similarly, users should be allowed to enter only double values in the Annual interest rate: JTextField. If the user enters anything besides a double, a message should be displayed instructing the user to enter a double value between 0.0 and 100.0. The interest rate should be entered such that an input of 5 is equal to 5%.
24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.1 Running the completed Enhanced Car Payment Calculator application.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.2 Entering a double in the Down payment: JTextField.
24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.3 Message dialog displayed for incorrect down payment input.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.4 Entering a non-numeric character in the Down payment: JTextField.
24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.5 Entering a non-numeric character in the Annual interest rate: JTextField.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.1 Test-Driving the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.6 Displaying monthly payments after input is corrected.
24.2 Introduction to Exception Handling
Perform a task
If the preceding task did not execute correctly Perform error processing
Perform next task
If the preceding task did not execute correctly Perform error processing
…
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.2 Introduction to Exception Handling (Cont.)
• A method throws an exception
– A problem occurs during the method execution – Unable to correct the problem
• Exception handler
– Executes when the application detects an exception
• Uncaught exception
– Does not have an exception handler
– Might cause an application to terminate execution
24.3 Exception Handling in Java
• try block
– Statements that might cause exceptions
– Statements that should not execute if an exception occurs
• Catch block
– Exception parameter
• Interact with the caught exception
• finally block
– Always executes
• throws clause
– Specifies the exceptions the method throws
– Appears after the parameter list and before the method body
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Java Exception Hierarchy
• Throwable class
– Superclass of all exceptions
– Only these objects can be used with the exception-handling mechanism
– Exception subclass of Throwable class
• Should be caught by the application – Error subclass of Throwable class
• Should not be caught by applications
24.4 Java Exception Hierarchy (Cont.)
Figure 24.7 Inheritance hierarchy for class Throwable.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.4 Java Exception Hierarchy (Cont.)
• Checked Exception
– Are not subclasses of RuntimeException
• Unchecked Exception
– Are subclasses of RuntimeException
• catch-or-declare requirement
– Compiler checks whether the method throws checked exceptions
– Compiler ensures that the checked exception is caught in a
catch block
24.5 Constructing the Enhanced Car Payment Calculator Application
When the user clicks the Calculate JButton
Clear the JTextArea of any previous text Get the car price from the priceJTextField
Get the down payment from the downPaymentJTextField Get the annual interest rate from the interestRateJTextField If the user provided valid input
Calculate the loan amount (price minus down payment)
Calculate the monthly interest rate (annual interest rate divided by 1200) Else
Display the error message dialog Calculate the monthly payment
Initialize the loan length to two years
While the loan length is less than or equal to five years
Calculate the number of months (loan length times 12)
Calculate the monthly payment based on loan amount, monthly interest rate and loan length in months
Display the result
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)
Action Component/Class Event/Method
Label all the application’s components priceJLabel,
downPaymentJLabel,
interestRateJLabel
Click the Calculate JButton calculateJButton User clicks
CalculateJButton
Clear the JTextArea monthlyPaymentsJTextArea
Get the car price priceJTextField
Get the down payment downPaymentJTextField
Get the annual interest rate interestRateJTextField
Display error message dialog
(JOptionPane.showMessageDialog)
JOptionPane
Display result monthlyPaymentsJTextArea
Figure 24.8 Enhanced Car Payment Calculator application ACE table.
24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.9 Obtaining the user input.
Get ints from
priceJTextField
and downPayment- JTextField
Get double from
interestRate- JTextField
• NumberFormatException class
– Subclass of
RuntimeException– Thrown when the application cannot convert a string to a desired
numeric type, such as
intor
double.
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.10 Creating a try statement in the calculateJButton event handler.
Adding a try
statement
24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.11 Adding a catch block.
Adding a
catch block
© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.
24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.12 Displaying an error message dialog.
Displaying an error message dialog
24.5 Constructing the Enhanced Car Payment Calculator Application (Cont.)
Figure 24.13 Error message dialog displayed when NumberFormatException occurs.
2004 Prentice Hall, Inc.
All rights reserved.
Outline
CarPayment.java (1 of 9)
2 // This application uses exception-handling to handle invalid input.
3 import java.awt.*;
4 import java.text.DecimalFormat;
5 import java.awt.event.*;
6 import javax.swing.*;
7
8 public class CarPayment extends JFrame 9 {
10 // JLabel and JTextField for price 11 private JLabel priceJLabel;
12 private JTextField priceJTextField;
13
14 // JLabel and JTextField for down payment 15 private JLabel downPaymentJLabel;
16 private JTextField downPaymentJTextField;
17
18 // JLabel and JTextField for interest rate 19 private JLabel interestRateJLabel;
20 private JTextField interestRateJTextField;
21
22 // JButton to calculate the monthly payments 23 private JButton calculateJButton;
24
Outline
CarPayment.java (2 of 9)
26 private JTextArea monthlyPaymentsJTextArea;
27
28 // no-argument constructor 29 public CarPayment()
30 {
31 createUserInterface();
32 } 33
34 // create and position GUI components; register event handlers 35 private void createUserInterface()
36 {
37 // get content pane and set layout to null 38 Container contentPane = getContentPane();
39
40 // enable explicit positioning of GUI components 41 contentPane.setLayout( null );
42
43 // set up priceJLabel
44 priceJLabel = new JLabel();
45 priceJLabel.setBounds( 40, 24, 80, 21 );
46 priceJLabel.setText( "Price:" );
47 contentPane.add( priceJLabel );
48
2004 Prentice Hall, Inc.
All rights reserved.
Outline
CarPayment.java (3 of 9)
50 priceJTextField = new JTextField();
51 priceJTextField.setBounds( 184, 24, 56, 21 );
52 priceJTextField.setHorizontalAlignment( JTextField.RIGHT );
53 contentPane.add( priceJTextField );
54
55 // set up downPaymentJLabel
56 downPaymentJLabel = new JLabel();
57 downPaymentJLabel.setBounds( 40, 56, 96, 21 );
58 downPaymentJLabel.setText( "Down payment:" );
59 contentPane.add( downPaymentJLabel );
60
61 // set up downPaymentJTextField
62 downPaymentJTextField = new JTextField();
63 downPaymentJTextField.setBounds( 184, 56, 56, 21 );
64 downPaymentJTextField.setHorizontalAlignment(
65 JTextField.RIGHT );
66 contentPane.add( downPaymentJTextField );
67
68 // set up interestRateJLabel
69 interestRateJLabel = new JLabel();
70 interestRateJLabel.setBounds( 40, 88, 120, 21 );
71 interestRateJLabel.setText( "Annual interest rate:" );
72 contentPane.add( interestRateJLabel );
73
Outline
CarPayment.java (4 of 9)
75 interestRateJTextField = new JTextField();
76 interestRateJTextField.setBounds( 184, 88, 56, 21 );
77 interestRateJTextField.setHorizontalAlignment(
78 JTextField.RIGHT );
79 contentPane.add( interestRateJTextField );
80
81 // set up calculateJButton
82 calculateJButton = new JButton();
83 calculateJButton.setBounds( 92, 128, 94, 24 );
84 calculateJButton.setText( "Calculate" );
85 contentPane.add( calculateJButton );
86 calculateJButton.addActionListener(
87
88 new ActionListener() // anonymous inner class 89 {
90 // event handler called when calculateJButton is clicked 91 public void actionPerformed( ActionEvent event )
92 {
93 calculateJButtonActionPerformed( event );
94 } 95
2004 Prentice Hall, Inc.
All rights reserved.
Outline
CarPayment.java (5 of 9)
97
98 ); // end call to addActionListener 99
100 // set up monthlyPaymentsJTextArea
101 monthlyPaymentsJTextArea = new JTextArea();
102 monthlyPaymentsJTextArea.setEditable( false );
103 monthlyPaymentsJTextArea.setBounds( 28, 168, 232, 90 );
104 contentPane.add( monthlyPaymentsJTextArea );
105
106 // set properties of application’s window
107 setTitle( "Car Payment Calculator" ); // set title-bar string 108 setSize( 288, 302 ); // set window size
109 setVisible( true ); // display window 110
111 } // end method createUserInterface 112
113 // calculate the monthly car payments
114 private void calculateJButtonActionPerformed( ActionEvent event ) 115 {
116 // clear JTextArea
117 monthlyPaymentsJTextArea.setText( "" );
118
Outline
CarPayment.java (6 of 9)
120 try 121 {
122 // get an integer from priceJTextField 123 int price = Integer.parseInt( priceJTextField.getText() );
124
125 // get an integer from downPaymentJTextField 126 int downPayment = 127 Integer.parseInt( downPaymentJTextField.getText() );
128
129 // get a double from interestRateJTextField 130 double interest = 131 Double.parseDouble( interestRateJTextField.getText() );
132
133 // create table of options over different periods of time 134 processData( price, downPayment, interest );
135 }
136 catch ( NumberFormatException exception ) 137 {
138 // integers were not input in the JTextFields 139 JOptionPane.showMessageDialog( this, 140 "Please enter integers for the price and down\n" + 141 "payment and a decimal number for the interest", 142 "Number Format Error", JOptionPane.ERROR_MESSAGE );
143 } 144
145 } // end method calculateJButtonActionPerformed
Enclosing the code that may cause exceptions in a try
block
Add a catch block to handle Number- FormatException
2004 Prentice Hall, Inc.
All rights reserved.
Outline
CarPayment.java (7 of 9)
147 // process entered data and calculate payments over 148 // each time interval
149 private void processData( int price, int downPayment, 150 double interest )
151 {
152 // calculate loan amount and monthly interest 153 int loanAmount = price - downPayment;
154 double monthlyInterest = interest / 1200;
155
156 // format to display monthlyPayment in currency format 157 DecimalFormat dollars = new DecimalFormat( "$0.00" );
158
159 int years = 2; // repetition counter 160
161 // add header JTextArea
162 monthlyPaymentsJTextArea.append( "Months\tMonthly Payments" );
163
164 // while years is less than or equal to five years 165 while ( years <= 5 )
166 {
167 // calculate payment period 168 int months = 12 * years;
Outline
CarPayment.java (8 of 9)
170 // get monthlyPayment
171 double monthlyPayment = calculateMonthlyPayment(
172 monthlyInterest, months, loanAmount );
173
174 // insert result into JTextArea
175 monthlyPaymentsJTextArea.append( "\n" + months + "\t" + 176 dollars.format( monthlyPayment ) );
177
178 years++; // increment counter 179
180 } // end while 181
182 } // end method processData 183
184 // calculate monthlyPayment
185 private double calculateMonthlyPayment( double monthlyInterest, 186 int months, int loanAmount )
187 {
188 double base = Math.pow( 1 + monthlyInterest, months );
189 return loanAmount * monthlyInterest / ( 1 - ( 1 / base ) );
190
191 } // end method calculateMonthlyPayment 192
2004 Prentice Hall, Inc.
All rights reserved.
Outline
CarPayment.java (9 of 9)
194 public static void main( String [] args ) 195 {
196 CarPayment application = new CarPayment();
197 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
198
199 } // end method main 200
201 } // end class CarPayment