© Copyright 1992-2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Outline DivideByZeroTes t.java 1 // Fig. 15.1: DivideByZeroTest.java 2 // An exception-handling example that checks for divide-by-zero. 3 import java.awt.*;
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 15.1 Test-Driving the Craps Game Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 14.1 Test-Driving the Fund Raiser Application.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 8 - Interest Calculator Application: Introducing.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 7 – Class Average Application: Introducing.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 6 – Car Payment Calculator Application: Introducing.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 6.1 Test-Driving the Wage Calculator Application.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 9 Car Payment Calculator Application Introducing the Do While...Loop and Do Until...Loop.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 16.1 Test-Driving the Flag Quiz Application.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 8 - Interest Calculator Application: Introducing.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 5 – Dental Payment Application: Introducing.
Java Programming: Guided Learning with Early Objects
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 6 – Car Payment Calculator Application: Introducing.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 18.1 Test-Driving the Microwave Oven Application.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 19.1 Test-Driving the Shipping Hub Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 23.1 Test-Driving the Screen Scraping Application.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 25 – Ticket Information Application Introducing.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Class Average Application Introducing the Do...Loop While and Do...Loop Until.
© Copyright 1992–2005 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Tutorial 7 – Class Average Application: Introducing.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 22.1 Test-Driving the Typing Skills Developer.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 12 – Enhancing the Wage Calculator Application.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 8.1 Test-Driving the Car Payment Calculator.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 11.1 Test-Driving the Security Panel Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 10.1 Test-Driving the Interest Calculator.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 13.1 Test-Driving the Enhanced Interest Calculator.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 2 – Welcome Application Introduction to Graphical.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 4 – Completing the Inventory Application.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 5.1 Test-Driving the Enhanced Inventory Application.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 17.1 Test-Driving the Student Grades Application.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 28.1 Java Speech API 28.2 Downloading and.
 2003 Prentice Hall, Inc. All rights reserved. 1 Outline 11.1 Test-Driving the Interest Calculator Application 11.2 Essentials of Counter-Controlled Repetition.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 7.1 Test-Driving the Dental Payment Application.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Chapter 14 – Exception Handling
“Form Ever Follows Function” Louis Henri Sullivan
Tutorial 9 - Car Payment Calculator Application Introducing the while Repetition Statement Outline 9.1 Test-Driving the Car Payment Calculator Application.
Chapter 15 – Exception Handling
Presentation transcript:

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 24.1 Test-Driving the Enhanced Car Payment Calculator Application 24.2Introduction to Exception Handling 24.3Exception Handling in Java 24.4Java Exception Hierarchy 24.5Constructing the Enhanced Car Payment Calculator Application 24.6Wrap-Up Tutorial 24 – Enhanced Car Payment Calculator Application Introducing Exception Handling

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 2 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Enhanced Car Payment Calculator Application

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.1 Running the completed Enhanced Car Payment Calculator application.

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.2 Entering a double in the Down payment: JTextField.

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.3 Message dialog displayed for incorrect down payment input.

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.4 Entering a non-numeric character in the Down payment: JTextField.

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.5 Entering a non-numeric character in the Annual interest rate: JTextField.

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Test-Driving the Enhanced Car Payment Calculator Application (Cont.) Figure 24.6 Displaying monthly payments after input is corrected.

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Java Exception Hierarchy (Cont.) Figure 24.7 Inheritance hierarchy for class Throwable.

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved 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 Increment the loan length in years by one year

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Enhanced Car Payment Calculator Application (Cont.)

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure 24.9 Obtaining the user input. Get int s 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 int or double.

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure Creating a try statement in the calculateJButton event handler. Adding a try statement

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure Adding a catch block. Adding a catch block

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure Displaying an error message dialog. Displaying an error message dialog

© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved Constructing the Enhanced Car Payment Calculator Application (Cont.) Figure Error message dialog displayed when NumberFormatException occurs.

 2004 Prentice Hall, Inc. All rights reserved. Outline 23 CarPayment.java (1 of 9) 1 // Tutorial 24: CarPayment.java 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; // JLabel and JTextField for down payment 15 private JLabel downPaymentJLabel; 16 private JTextField downPaymentJTextField; // JLabel and JTextField for interest rate 19 private JLabel interestRateJLabel; 20 private JTextField interestRateJTextField; // JButton to calculate the monthly payments 23 private JButton calculateJButton; 24

 2004 Prentice Hall, Inc. All rights reserved. Outline 24 CarPayment.java (2 of 9) 25 // JTextArea to display the monthly payments 26 private JTextArea monthlyPaymentsJTextArea; // no-argument constructor 29 public CarPayment() 30 { 31 createUserInterface(); 32 } // 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(); // enable explicit positioning of GUI components 41 contentPane.setLayout( null ); // 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 25 CarPayment.java (3 of 9) 49 // set up priceJTextField 50 priceJTextField = new JTextField(); 51 priceJTextField.setBounds( 184, 24, 56, 21 ); 52 priceJTextField.setHorizontalAlignment( JTextField.RIGHT ); 53 contentPane.add( priceJTextField ); // set up downPaymentJLabel 56 downPaymentJLabel = new JLabel(); 57 downPaymentJLabel.setBounds( 40, 56, 96, 21 ); 58 downPaymentJLabel.setText( "Down payment:" ); 59 contentPane.add( downPaymentJLabel ); // set up downPaymentJTextField 62 downPaymentJTextField = new JTextField(); 63 downPaymentJTextField.setBounds( 184, 56, 56, 21 ); 64 downPaymentJTextField.setHorizontalAlignment( 65 JTextField.RIGHT ); 66 contentPane.add( downPaymentJTextField ); // 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

 2004 Prentice Hall, Inc. All rights reserved. Outline 26 CarPayment.java (4 of 9) 74 // set up interestRateJTextField 75 interestRateJTextField = new JTextField(); 76 interestRateJTextField.setBounds( 184, 88, 56, 21 ); 77 interestRateJTextField.setHorizontalAlignment( 78 JTextField.RIGHT ); 79 contentPane.add( interestRateJTextField ); // 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( 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 27 CarPayment.java (5 of 9) 96 } // end anonymous inner class ); // end call to addActionListener // set up monthlyPaymentsJTextArea 101 monthlyPaymentsJTextArea = new JTextArea(); 102 monthlyPaymentsJTextArea.setEditable( false ); 103 monthlyPaymentsJTextArea.setBounds( 28, 168, 232, 90 ); 104 contentPane.add( monthlyPaymentsJTextArea ); // 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 } // end method createUserInterface // calculate the monthly car payments 114 private void calculateJButtonActionPerformed( ActionEvent event ) 115 { 116 // clear JTextArea 117 monthlyPaymentsJTextArea.setText( "" ); 118

 2004 Prentice Hall, Inc. All rights reserved. Outline 28 CarPayment.java (6 of 9) 119 // try to retrieve price and down payment 120 try 121 { 122 // get an integer from priceJTextField 123 int price = Integer.parseInt( priceJTextField.getText() ); // get an integer from downPaymentJTextField 126 int downPayment = 127 Integer.parseInt( downPaymentJTextField.getText() ); // get a double from interestRateJTextField 130 double interest = 131 Double.parseDouble( interestRateJTextField.getText() ); // 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" "payment and a decimal number for the interest", 142 "Number Format Error", JOptionPane.ERROR_MESSAGE ); 143 } } // 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 29 CarPayment.java (7 of 9) // 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; // format to display monthlyPayment in currency format 157 DecimalFormat dollars = new DecimalFormat( "$0.00" ); int years = 2; // repetition counter // add header JTextArea 162 monthlyPaymentsJTextArea.append( "Months\tMonthly Payments" ); // while years is less than or equal to five years 165 while ( years <= 5 ) 166 { 167 // calculate payment period 168 int months = 12 * years;

 2004 Prentice Hall, Inc. All rights reserved. Outline 30 CarPayment.java (8 of 9) // get monthlyPayment 171 double monthlyPayment = calculateMonthlyPayment( 172 monthlyInterest, months, loanAmount ); // insert result into JTextArea 175 monthlyPaymentsJTextArea.append( "\n" + months + "\t" dollars.format( monthlyPayment ) ); years++; // increment counter } // end while } // end method processData // 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 ) ); } // end method calculateMonthlyPayment 192

 2004 Prentice Hall, Inc. All rights reserved. Outline 31 CarPayment.java (9 of 9) 193 // main method 194 public static void main( String [] args ) 195 { 196 CarPayment application = new CarPayment(); 197 application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } // end method main } // end class CarPayment