Download presentation
Presentation is loading. Please wait.
Published byMadeline Fields Modified over 9 years ago
1
Java Programming: Guided Learning with Early Objects
Chapter 10 Exception Handling and Events
2
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
3
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
4
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
5
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
6
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
7
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
8
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
9
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
10
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
11
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
12
Table 10-1 Commonly Used Constructors and Methods of the class Throwable
Java Programming: Guided Learning with Early Objects
13
Figure 10-2 The class Exception and some of its subclasses from the package java.lang
Java Programming: Guided Learning with Early Objects
14
Figure 10-3 The class Exception and some of its subclasses from the package java.util
Java Programming: Guided Learning with Early Objects
15
Figure 10-4 The class IOException and some of its subclasses from the package java.io
Java Programming: Guided Learning with Early Objects
16
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
17
Table 10-2 class Exception and its Constructors
Java Programming: Guided Learning with Early Objects
18
Table 10-3 Commonly Used Exception Classes
Java Programming: Guided Learning with Early Objects
19
Table 10-3 Commonly Used Exception Classes (continued)
Java Programming: Guided Learning with Early Objects
20
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
21
Table 10-6 class InputMistmatchException and its Constructors
Java Programming: Guided Learning with Early Objects
22
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
23
Table 10-9 Exceptions Thrown by the Method hasNext
Table Exceptions Thrown by the Methods of the class Integer Java Programming: Guided Learning with Early Objects
24
Table 10-11 Exceptions Thrown by the Methods of the class Double
Java Programming: Guided Learning with Early Objects
25
Table 10-12 Exceptions Thrown by the Methods of the class String
Java Programming: Guided Learning with Early Objects
26
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
27
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
28
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
29
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
30
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
31
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
32
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
33
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
34
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
35
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
36
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
37
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
38
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
39
Table 10-14 Events Generated by key Components
Java Programming: Guided Learning with Early Objects
40
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
41
Table 10-15 Events Generated by mouse Components
Java Programming: Guided Learning with Early Objects
42
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
43
Table 10-16 The Constructor and Commonly Used Methods of class Timer
Java Programming: Guided Learning with Early Objects
44
Table 10-16 The Constructor and Commonly Used Methods of class Timer (continued)
Java Programming: Guided Learning with Early Objects
45
Figure 10-10 An interface for showing the position of a ball
Java Programming: Guided Learning with Early Objects
46
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
47
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
48
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
49
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
50
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.