Title: Java Programming: Guided Learning with Early Objects
1Java Programming Guided Learning with Early
Objects
- Chapter 10
- Exception Handling and Events
2Objectives
- 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
3Objectives (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
4Handling 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
5Javas 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
6try/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
7try/catch/finally Block (continued)
- Syntax
- try
- //statements
-
- catch (ExceptionClassName1 objRef1)
- // exception handler code
-
-
- catch (ExceptionClassNameN objRefN)
- // exception handler code
-
- finally // statements
8try/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
9Order 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
10Using 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
11Java 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
12Table 10-1 Commonly Used Constructors and Methods
of the class Throwable
13Figure 10-2 The class Exception and some of its
subclasses from the package java.lang
14Figure 10-3 The class Exception and some of its
subclasses from the package java.util
15Figure 10-4 The class IOException and some of its
subclasses from the package java.io
16Javas 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
17Table 10-2 class Exception and its Constructors
18Table 10-3 Commonly Used Exception Classes
19Table 10-3 Commonly Used Exception Classes
(continued)
20Table 10-4 Exceptions Thrown by the Method nextInt
Table 10-5 Exceptions Thrown by the Method
nextDouble
21Table 10-6 class InputMistmatchException and its
Constructors
22Table 10-7 Exceptions Thrown by the Method next
Table 10-8 Exceptions Thrown by the Method
nextLine
23Table 10-9 Exceptions Thrown by the Method hasNext
Table 10-10 Exceptions Thrown by the Methods of
the class Integer
24Table 10-11 Exceptions Thrown by the Methods of
the class Double
25Table 10-12 Exceptions Thrown by the Methods of
the class String
26Checked and Unchecked Exceptions
- Checked 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
27More 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
28class 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
29Rethrowing 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
30Rethrowing 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)
31Method 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
32Exception-Handling Techniques
- When exception occurs, programmer has three
choices - Terminate the program
- Fix the error and continue
- Log the error and continue
33Terminate the Program
- In some cases, best to terminate when exception
occurs - Example
- Input data from file
- File not found
- No point in continuing
34Fix 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
35Log 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
36Creating 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
37GUI 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
38Key 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
39Table 10-14 Events Generated by key Components
40Mouse Events
- Mouse generates seven events
- mouseClicked
- mouseEntered
- mouseExited
- mousePressed
- mouseReleased
- mouseDragged
- mouseMoved
- Events handled by MouseListener and
MouseMotionListener
41Table 10-15 Events Generated by mouse Components
42Timer 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
43Table 10-16 The Constructor and Commonly Used
Methods of class Timer
44Table 10-16 The Constructor and Commonly Used
Methods of class Timer (continued)
45Figure 10-10 An interface for showing the
position of a ball
46Summary
- 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
47Summary (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
48Summary (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
49Summary (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
50Summary (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