Chapter 11 - Handling Exceptions and Events

54
Java Programming: From Problem Analysis to Program Design, 5e Chapter 11 Handling Exceptions and Events

description

 

Transcript of Chapter 11 - Handling Exceptions and Events

Page 1: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e

Chapter 11Handling Exceptions and Events

Page 2: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 2

Chapter Objectives

• Learn what an exception is• See how a try/catch block is used to

handle exceptions• Become aware of the hierarchy of exception

classes• Learn about checked and unchecked

exceptions

Page 3: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 3

Chapter Objectives (continued)

• Learn how to handle exceptions within a program

• Discover how to throw and rethrow an exception

• Learn how to handle events in a program

Page 4: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 4

Exception

• Definition: an occurrence of an undesirable situation that can be detected during program execution

• Examples– Division by zero– Trying to open an input file that does not exist– An array index that goes out of bounds

Page 5: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 5

Handling Exception within a Program

• Can use an if statement to handle an exception

• However, suppose that division by zero occurs in more than one place within the same block– In this case, using if statements may not be the

most effective way to handle the exception

Page 6: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 6

Java’s Mechanism of Exception Handling

• When an exception occurs, an object of a particular exception class is created

• Java provides a number of exception classes to effectively handle certain common exceptions such as division by zero, invalid input, and file not found

• Division by zero is an arithmetic error and is handled by the class ArithmeticException

Page 7: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 7

Java’s Mechanism of Exception Handling (continued)

• When a division by zero exception occurs, the program creates an object of the class ArithmeticException

• When a Scanner object is used to input data into a program, any invalid input errors are handled using the class InputMismatchException

• The class Exception (directly or indirectly) is the superclass of all the exception classes in Java

Page 8: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 8

try/catch/finally Block• Statements that might generate an exception are

placed in a try block

• The try block might also contain statements that should not be executed if an exception occurs

• The try block is followed by zero or more catch blocks

• A catch block specifies the type of exception it can catch and contains an exception handler

Page 9: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 9

try/catch/finally Block (continued)

• The last catch block may or may not be followed by a finally block

• Any code contained in a finally block always executes, regardless of whether an exception occurs, except when the program exits early from a try block by calling the method System.exit

• If a try block has no catch block, then it must have the finally block

Page 10: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 10

try/catch/finally Block (continued)

Page 11: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 11

try/catch/finally Block (continued)

•If no exception is thrown in a try block, all catch blocks associated with the try block are ignored and program execution resumes after the last catch block•If an exception is thrown in a try block, the remaining statements in the try block are ignored

- The program searches the catch blocks in the order in which they appear after the try block and looks for an appropriate exception handler

Page 12: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 12

try/catch/finally Block (continued)

• If the type of the thrown exception matches the parameter type in one of the catch blocks, the code of that catch block executes and the remaining catch blocks after this catch block are ignored

• If there is a finally block after the last catch block, the finally block executes regardless of whether an exception occurs

Page 13: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 13

Order of catch Blocks

• The heading of a catch block specifies the type of exception it handles

• A catch block can catch either all exceptions of a specific type or all types of exceptions

• A reference variable of a superclass type can point to an object of its subclass

Page 14: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 14

Order of catch Blocks (continued)

• If in the heading of a catch block you declare an exception using the class Exception, then that catch block can catch all types of exceptions because the class Exception is the superclass of all exception classes

• In a sequence of catch blocks following a try block, a catch block declaring an exception of a subclass type should be placed before catch blocks declaring exceptions of a superclass type

Page 15: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 15

Java Exception Hierarchy

Page 16: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 16

Java Exception Hierarchy (continued)

Page 17: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 17

Java Exception Hierarchy (continued)

Page 18: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 18

Java Exception Hierarchy (continued)

Page 19: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 19

Java Exception Hierarchy (continued)

Page 20: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 20

Java’s Exception Class• class Exception

– Subclass of class Throwable – Superclass of classes designed to handle

exceptions

• Various types of exceptions– I/O exceptions– Number format exceptions– File not found exceptions– Array index out of bounds exceptions

• Various exceptions categorized into separate classes and contained in various packages

Page 21: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 21

The class Exception and its Constructors

Page 22: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 22

Java Exception Classes

Page 23: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 23

Java Exception Classes (continued)

Page 24: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 24

Java Exception Classes (continued)

Page 25: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 25

Java Exception Classes (continued)

Page 26: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 26

Java Exception Classes (continued)

Page 27: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 27

Java Exception Classes (continued)

Page 28: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 28

Java Exception Classes (continued)

Page 29: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 29

Java Exception Classes (continued)

Page 30: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 30

Checked Exceptions

• Definition: any exception that can be recognized by the compiler

• Examples– FileNotFoundExceptions

Page 31: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 31

Unchecked Exceptions• Definition: exceptions that cannot be recognized

when the program compiles (must be checked for by programmer)

• Examples– Division by zero– Array index out of bounds

• Syntax

• ExceptionType1, ExceptionType2, and so on are names of exception classes

Page 32: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 32

Exceptions Example Code

public static void exceptionMethod() throws InputMismatchException, FileNotFoundException{ //statements}

• The method exceptionMethod throws exceptions of the type InputMismatchException and FileNotFoundException

Page 33: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 33

The class Exception and the Operator instanceof

• A reference of a superclass type can point to objects of its subclass

• You can determine if a reference variable points to an object using the operator instanceof

• You can combine catch blocks using this facility

Page 34: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 34

try {

System.out.print("Line 4: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 7: Enter the " + "divisor: "); divisor = console.nextInt(); System.out.println(); quotient = dividend / divisor; System.out.println("Line 11: Quotient = " + quotient); }

catch (Exception eRef){

if (eRef instanceof ArithmeticException) System.out.println("Line 14: Exception " + eRef.toString()); else if (eRef instanceof InputMismatchException) System.out.println("Line 16: Exception " + eRef.toString()); }

The class Exception and the Operator instanceof (continued)

Page 35: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 35

Rethrowing and Throwing an Exception

• When an exception occurs in a try block, control immediately passes to one of the catch blocks; typically, a catch block does one of the following:– Completely handles the exception– Partially processes the exception; in this case,

the catch block either rethrows the same exception or throws another exception for the calling environment to handle the exception

– Rethrows the same exception for the calling environment to handle the exception

Page 36: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 36

Rethrowing and Throwing an Exception (continued)

• Useful when: – Catch block catches exception but is unable to

handle it– Catch block decides exception should be

handled by calling environment

• Allows programmer to provide exception-handling code in one place

• Syntaxthrow exceptionReference;

Page 37: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 37

import java.util.*;public class RethrowExceptionExmp1{ static Scanner console = new Scanner(System.in); public static void main(String[] args) { int number; try { number = getNumber(); System.out.println("Line 5: number = " + number); } catch (InputMismatchException imeRef) { System.out.println("Line 7: Exception " + imeRef.toString()); } }}

Rethrowing and Throwing an Exception (continued)

Page 38: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 38

public static int getNumber() throws InputMismatchException { int num; try { System.out.print("Line 11: Enter an “ + "integer: "); num = console.nextInt(); System.out.println(); return num; } catch (InputMismatchException imeRef) { throw imeRef; } }}

Rethrowing and Throwing an Exception (continued)

Page 39: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 39

The Method printStackTrace

• Used to determine the order in which the methods were called and where the exception was handled

Page 40: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 40

import java.io.*;public class PrintStackTraceExample1{ public static void main(String[] args) { try { methodA(); } catch (Exception e) { System.out.println(e.toString() + " caught in main"); e.printStackTrace(); } }

The Method printStackTrace (continued)

Page 41: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 41

public static void methodA() throws Exception { methodB(); } public static void methodB() throws Exception { methodC(); } public static void methodC() throws Exception { throw new Exception("Exception generated " + "in method C"); }}

The Method printStackTrace (continued)

Page 42: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 42

• Sample Runjava.lang.Exception: Exception generated in method C caught in mainjava.lang.Exception: Exception generated in method C at PrintStackTraceExample1.methodC (PrintStackTraceExample1.java:30) at PrintStackTraceExample1.methodB (PrintStackTraceExample1.java:25) at PrintStackTraceExample1.methodA (PrintStackTraceExample1.java:20) at PrintStackTraceExample1.main (PrintStackTraceExample1.java:9)

The Method printStackTrace (continued)

Page 43: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 43

Exception-Handling Techniques

• Terminate program– Output appropriate error message upon

termination

• Fix error and continue– Repeatedly get user input– Output appropriate error message until valid

value is entered

• Log error and continue– Write error messages to file and continue with

program execution

Page 44: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 44

Creating Your Own Exception Classes

• Exception class you define extends class Exception or one of its subclasses

• Syntax to throw your own exception object:

throw new ExceptionClassName(messageString);

Page 45: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 45

Creating Your Own Exception Classes (continued)

public class MyDivisionByZeroException extends Exception{ public MyDivisionByZeroException() { super("Cannot divide by zero"); }

public MyDivisionByZeroException(String strMessage) { super(strMessage); }}

Page 46: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 46

Event Handling

• Action events – Handled by implementing interface ActionListener

• Window events – Handled by implementing interface WindowListener

• Mouse events – Handled by implementing interface MouseListener

• Key events – Handled by implementing interface KeyListener

Page 47: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 47

Event Handling (continued)

• class WindowAdapter – Implements interface WindowListener

with empty bodies to methods

• class MouseAdapter – Implements interface MouseListener

with empty bodies to methods

Page 48: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 48

Registering Listeners

• Registering window listener object to GUI component– Use method addWindowListener– Window listener object being registered is passed

as parameter to method addWindowListener

• Registering mouse listener object to GUI component– Use method addMouseListener– Mouse listener object being registered is passed

as parameter to method addMouseListener

Page 49: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 49

Event Handling (continued)

Page 50: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 50

Event Handling (continued)

Page 51: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 51

Event Handling (continued)

Page 52: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 52

Programming Example: Calculator

Page 53: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 53

Chapter Summary• Exception

– Definition

• Handling exceptions within a program– try/catch/finally block– Order of catch blocks– Using try/catch blocks in a program– The class Exception and the operator instanceof

– Rethrowing and throwing an exception

• Exception– Hierarchy – Classes

Page 54: Chapter 11 - Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, 5e 54

Chapter Summary (continued)

• Checked and unchecked exceptions• The method printStackTrace• Exception-handling techniques

– Terminate program– Fix error and continue– Log error and continue

• Creating your own exception classes• Event handling