Java Programming: Guided Learning with Early Objects

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.
CS102--Object Oriented Programming
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
COMP 121 Week 5: Exceptions and Exception Handling.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
 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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
Event Handling Events and Listeners Timers and Animation.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions CIS 304 Intermediate Java Programming for Business.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
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 24.1 Test-Driving the Enhanced Car Payment.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved Enhanced Car Payment Calculator Application Introducing Exception Handling.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Chapter 14 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Chapter 14: Exception Handling
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Lecture 11 Objectives Learn what an exception is.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 15 – Exception Handling
Presentation transcript:

Java Programming: Guided Learning with Early Objects Chapter 10 Exception Handling and Events

Objectives Learn what an exception is Learn how to use a try/catch block to handle exceptions Become acquainted with the hierarchy of exception classes Learn about checked and unchecked exceptions Learn how to handle exceptions within a program Java Programming: Guided Learning with Early Objects

Objectives (continued) Discover how to rethrow and throw an exception Become familiar with the adapter classes Learn how to handle key and mouse events Learn how to use the Timer class Java Programming: Guided Learning with Early Objects

Handling Exceptions within a Program Recall when you try to input incompatible data into a variable, the program terminates Generates exception Example: Divide by zero generates ArithmeticException: / by zero Exception could be prevented by checking that divisor is not zero before dividing Add an if statement Java Programming: Guided Learning with Early Objects

Java’s Mechanism of Exception Handling Using if statements may not be appropriate or convenient to handle exceptions Put exception code in one place Easier to modify exception-handling code When exception occurs, object of exception class created Java provides several exception classes class Exception is the superclass to all exception classes in Java Java Programming: Guided Learning with Early Objects

try/catch/finally Block try block: Contains statements that might generate exception Contains statements that should not be executed if exception occurs Followed by zero or more catch blocks catch block: Specifies type of exception to catch Contains an exception handler finally block: code always executes Java Programming: Guided Learning with Early Objects

try/catch/finally Block (continued) Syntax: try { //statements } catch (ExceptionClassName1 objRef1) { // exception handler code … catch (ExceptionClassNameN objRefN) { finally { // statements } Java Programming: Guided Learning with Early Objects

try/catch/finally Block (continued) If no exception thrown in try block, all catch blocks ignored Execution resumes after last catch block If exception thrown in try block, remaining statements ignored Program searches catch blocks in order, looking for a matching catch block finally block executes regardless of exception finally block is optional Java Programming: Guided Learning with Early Objects

Order of catch Blocks Can catch all exceptions of a specific type or all types of exceptions Heading of catch block specifies types of exceptions it handles If heading declares exception using class Exception, catch block catches all types When exception caught by catch block, remaining catch blocks ignored Order is important Java Programming: Guided Learning with Early Objects

Using try/catch Blocks in a Program Common error while inputting numeric data is typing nonnumeric character Methods nextInt and nextDouble throw InputMismatchException Division by zero with integer values generates ArithmeticException When exception occurs, program throws an object of a specific exception class Java Programming: Guided Learning with Early Objects

Java Exception Hierarchy Every class can potentially cause exceptions class Throwable: Derived from class Object Superclass of class Exception Methods getMessage, printStackTrace, and toString are public Inherited by subclasses of class Throwable Java Programming: Guided Learning with Early Objects

Table 10-1 Commonly Used Constructors and Methods of the class Throwable Java Programming: Guided Learning with Early Objects

Figure 10-2 The class Exception and some of its subclasses from the package java.lang Java Programming: Guided Learning with Early Objects

Figure 10-3 The class Exception and some of its subclasses from the package java.util Java Programming: Guided Learning with Early Objects

Figure 10-4 The class IOException and some of its subclasses from the package java.io Java Programming: Guided Learning with Early Objects

Java’s Exception Classes class Exception is the superclass of Java exception-handling classes Java categorizes exceptions into separate classes Exception classes placed in the package that contains the methods that throw them Method getMessage returns string containing detailed message stored in exception object Java Programming: Guided Learning with Early Objects

Table 10-2 class Exception and its Constructors Java Programming: Guided Learning with Early Objects

Table 10-3 Commonly Used Exception Classes Java Programming: Guided Learning with Early Objects

Table 10-3 Commonly Used Exception Classes (continued) Java Programming: Guided Learning with Early Objects

Table 10-4 Exceptions Thrown by the Method nextInt Table 10-5 Exceptions Thrown by the Method nextDouble Java Programming: Guided Learning with Early Objects

Table 10-6 class InputMistmatchException and its Constructors Java Programming: Guided Learning with Early Objects

Table 10-7 Exceptions Thrown by the Method next Table 10-8 Exceptions Thrown by the Method nextLine Java Programming: Guided Learning with Early Objects

Table 10-9 Exceptions Thrown by the Method hasNext Table 10-10 Exceptions Thrown by the Methods of the class Integer Java Programming: Guided Learning with Early Objects

Table 10-11 Exceptions Thrown by the Methods of the class Double Java Programming: Guided Learning with Early Objects

Table 10-12 Exceptions Thrown by the Methods of the class String Java Programming: Guided Learning with Early Objects

Checked and Unchecked Exceptions Any exception the compiler can recognize Example: FileNotFoundException Compiler encounters statements to open a file Reduces number of statements not properly handled Unchecked exceptions: Any exception the compiler cannot recognize Examples: division by zero, index out of bounds Programmer checks for these exceptions Java Programming: Guided Learning with Early Objects

More Examples of Exception Handling Java accepts only strings as input in dialog boxes and text fields Methods parseInt, parseFloat, and parseDouble may terminate with number format error Throw NumberFormatException if string does not contain a number Java Programming: Guided Learning with Early Objects

class Exception and the Operator instanceof Recall that reference variable of superclass type can point to objects of its subclasses Operator instanceof determines if reference variable points to object of particular class Used to combine two catch blocks Java Programming: Guided Learning with Early Objects

Rethrowing or Throwing an Exception When exception occurs in try block, control passes to first matching catch block catch block may: Completely handle the exception Partially process the exception Rethrows same exception Throws another exception for calling environment to handle the exception Rethrow same exception for calling environment to handle Java Programming: Guided Learning with Early Objects

Rethrowing or Throwing an Exception (continued) Rethrowing an exception or throwing an exception handled by throw statement throw statement throws either checked or unchecked exception Exceptions are objects of a specific type Syntax to rethrow an exception: throw exceptionReference General throw syntax: throw new ExceptionClassName(messageStr); Java Programming: Guided Learning with Early Objects

Method printStackTrace Java keeps track of method call sequence class Exception subclass of class Throwable class Throwable contains public method printStackTrace Use method printStackTrace to determine the order in which methods were called Determine where exception handled Java Programming: Guided Learning with Early Objects

Exception-Handling Techniques When exception occurs, programmer has three choices: Terminate the program Fix the error and continue Log the error and continue Java Programming: Guided Learning with Early Objects

Terminate the Program In some cases, best to terminate when exception occurs Example: Input data from file File not found No point in continuing Java Programming: Guided Learning with Early Objects

Fix the Error and Continue Handle the exception, let the program continue Example: Prompt the user for a file name User misspells file name File not found Reprompt the user Java Programming: Guided Learning with Early Objects

Log the Error and Continue Sometimes terminating the program is unsafe or unnecessary Prefer to record the exception and continue Example: Analyzing airline-ticketing transactions Large volume of transactions each day Analysis program would take too long if it fixed every error Program records exceptions and continues processing transactions Java Programming: Guided Learning with Early Objects

Creating Your Own Exception Classes Java does not provide exception-handling classes for every possible circumstance Must throw programmer-defined exceptions using throw statement Define classes by extending the class Exception or a subclass Typically, constructors are the only methods included when defining exception class Programmer-defined classes inherit members of superclasses Java Programming: Guided Learning with Early Objects

GUI Adaptor Classes, Events, and the Timer Class (Optional) Java provides interfaces to handle events Cannot instantiate object of an interface Create an object to handle an event, and create a class that implements appropriate interface ActionListener handles action events WindowListener handles window events Class may implement more than one interface Java Programming: Guided Learning with Early Objects

Key Events Three types of key events: keyPressed keyReleased keyTyped keyTyped: generated when alphanumeric key pressed keyPressed: generated when meta key pressed keyReleased: generated when any key released Java Programming: Guided Learning with Early Objects

Table 10-14 Events Generated by key Components Java Programming: Guided Learning with Early Objects

Mouse Events Mouse generates seven events: mouseClicked mouseEntered mouseExited mousePressed mouseReleased mouseDragged mouseMoved Events handled by MouseListener and MouseMotionListener Java Programming: Guided Learning with Early Objects

Table 10-15 Events Generated by mouse Components Java Programming: Guided Learning with Early Objects

Timer Class Control activities over time No visual representation Cannot be displayed on screen Generate action events at specific time intervals Constructor sets delay time between events Second parameter specifies action event to be generated at time interval Java Programming: Guided Learning with Early Objects

Table 10-16 The Constructor and Commonly Used Methods of class Timer Java Programming: Guided Learning with Early Objects

Table 10-16 The Constructor and Commonly Used Methods of class Timer (continued) Java Programming: Guided Learning with Early Objects

Figure 10-10 An interface for showing the position of a ball Java Programming: Guided Learning with Early Objects

Summary Exception is an object of the exception class Java provides exception classes Programmer creates own exception classes try/catch/finally block handles exceptions in a program Statements that may generate exception placed in try block try block also contains statements that should not be executed in presence of exception Java Programming: Guided Learning with Early Objects

Summary (continued) try block followed by zero or more catch blocks catch block specifies type of exception caught and contains exception handler Last catch block may be followed by finally block finally block contains code that executes regardless of exception If try block not followed by catch block, must have finally block Java Programming: Guided Learning with Early Objects

Summary (continued) catch block catches all exceptions or specific type of exceptions Heading of catch block specifies the type of exception it handles class Exception is superclass of all exception-handling classes Contained in package java.lang Exception classes placed in package containing the methods that throw them Java Programming: Guided Learning with Early Objects

Summary (continued) Checked exception: any exception recognized by the compiler Unchecked exception: any exception not recognized by the compiler Programmer-defined exception classes extend class Exception class WindowAdapter implements interface WindowListener Provides empty bodies to methods Java Programming: Guided Learning with Early Objects

Summary (continued) Register a window listener using method addWindowListener A WindowListener object is passed as a parameter to addWindowListener Timer class objects control activities over time No visual representation Cannot be displayed on screen Generate action events at specific time intervals Java Programming: Guided Learning with Early Objects