chapter 12: handling exceptions and events

77
Chapter 12: Handling Chapter 12: Handling Exceptions and Events Exceptions and Events J J ava ava P P rogramming: rogramming: From Problem Analysis to From Problem Analysis to Program Design, Program Design, Second Edition Second Edition

Upload: lana

Post on 19-Jan-2016

93 views

Category:

Documents


3 download

DESCRIPTION

Chapter 12: Handling Exceptions and Events. J ava P rogramming: From Problem Analysis to Program Design, Second Edition. 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. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Chapter 12: Handling Exceptions and Events

Chapter 12: Handling Chapter 12: Handling Exceptions and EventsExceptions and Events

JJavaava PProgramming:rogramming:

From Problem Analysis to Program From Problem Analysis to Program Design, Design,

Second EditionSecond Edition

Page 2: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 2

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. 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 3: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 3

Exception

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 4: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 4

import java.util.*;

public class ExceptionExample1 { static Scanner console = new Scanner(System.in);

public static void main (String[] args) { int dividend, divisor, quotient;

System.out.print("Line 2: Enter the “ + "dividend: "); dividend = console.nextInt();

System.out.println(); System.out.print("Line 5: Enter the “ + "divisor: "); divisor = console.nextInt();;

System.out.println(); quotient = dividend / divisor;

System.out.println("Line 9: Quotient = “ + quotient); }}

Page 5: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 5

Sample Run2

Line 2: Enter the dividend: 24

Line 5: Enter the divisor: 0

Exception in thread "main“

java.lang.ArithmeticException: / by zero

at ExceptionExample1.main(ExceptionExample1.java:23)

Page 6: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 6

Sample Run3

Line 2: Enter the dividend: 2e

Exception in thread "main" java.util.InputMismatchException

at java.util.Scanner.throwFor(Scanner.java:819)

at java.util.Scanner.next(Scanner.java:1431)

at java.util.Scanner.nextInt(Scanner.java:2040)

at java.util.Scanner.nextInt(Scanner.java:2000)

at ExceptionExample1.main(ExceptionExample1.java:15)

Page 7: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 7

Handling Exceptions within a Program

Can use an if statement to handle an exception.

Page 8: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 8

import java.util.*;public class ExceptionExample2{ static Scanner console = new Scanner(System.in); public static void main (String[] args) { int dividend, divisor, quotient; System.out.print("Line 2: Enter the " + "dividend: "); dividend = console.nextInt(); System.out.println(); System.out.print("Line 5: Enter the " + "divisor: "); divisor = console.nextInt();; System.out.println();

if (divisor != 0) { quotient = dividend / divisor; System.out.println("Line 10: " + "Quotient = " + quotient); }else System.out.println("Line 11: Cannot " + "divide by zero.");

}}

Page 9: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 9

Handling Exceptions within a Program

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 10: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 10

Java’s Mechanism of Exception Handling

With exception handling, a program can continue executing after dealing with a problem.

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 File not found

Page 11: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 11

Java’s Mechanism of Exception Handling

Division by zero is:

An arithmetic error.

Handled by the class ArithmeticException.

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

Page 12: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 12

Java’s Mechanism of Exception Handling

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 13: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 13

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.

Is followed by zero or more catch blocks.

A catch block:

Specifies the type of exception it can catch.

Contains an exception handler.

Page 14: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 14

try/catch/finally Block

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 15: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 15

try/catch/finally Block

Page 16: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 16

try/catch/finally Block

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.

VIP
اذا كان فيه اكسبشن مايكمل باقي الكود اللي بالتراي
Page 17: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 17

try/catch/finally Block

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 are ignored.

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

Page 18: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 18

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 19: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 19

Order of catch Blocks

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

Page 20: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 20

Order of catch Blocks

In a sequence of catch blocks following a try block, a catch block that declares an exception of a subclass type should be placed before catch blocks that declare exceptions of a superclass type.

It is a syntax error if a catch that catches a superclass object is placed before a catch that catches an object of a subclass of that superclass

VIP
انتبه اني اعرف الاكسبشن السوبر في آخر الكاتش
Page 21: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 21

import java.util.*;public class ExceptionExample3{ static Scanner console = new Scanner(System.in);

public static void main (String[] args) { int dividend, divisor, quotient; 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; //line 10 System.out.println("Line 11: Quotient = " + quotient); } catch (ArithmeticException aeRef) //line 12 { System.out.println("Line 13: Exception " + aeRef.toString()); } catch (InputMismatchException imeRef) { System.out.println("Line 15: Exception " + imeRef.toString()); } }}

Page 22: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 22

Sample Run2

Line 4: Enter the dividend: 18

Line 7: Enter the divisor: 0

Line 13: Exception java.lang.ArithmeticException: / by zero

The statement in line 10 throws an ArithmeticException,which is caught by the catch block starting at Line 12.

Page 23: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 23

Sample Run3

Line 4: Enter the dividend: 2753

Line 7: Enter the divisor: 2f1

Line 15: Exception java.util.InputMismatchException

The statement in line 8 throws an

InputMismatchException. Tis exception is thrown by the

method nextInt of the class Scanner.

The catch block starting at Line 14 catches this exception .

Page 24: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 24

2f1 stays as the next input token in the input stream

If the input token is invalid, the method nextInt does not remove that input token from the input stream.

catch (InputMismatchException imeRef) {

String str; str = console.next(); System.out.println("Line 17: Exception "

+ imeRef.toString() + " " + str );

}

Page 25: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 25

Sample Run3

Line 4: Enter the dividend: 2753

Line 7: Enter the divisor: 2f1

Line 17: Exception java.util.InputMismatchException 2f1

Page 26: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 26

The exception classes provided by Java

Page 27: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 27

Order of catch Blocks

Page 28: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 28

Order of catch Blocks

Page 29: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 29

Order of catch Blocks

Page 30: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 30

Order of catch Blocks

Page 31: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 31

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 32: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 32

Java’s Exception Class

Page 33: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 33

Java’s Exception Class

Page 34: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 34

Java’s Exception Class

Page 35: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 35

Java’s Exception Class

Page 36: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 36

Java’s Exception Class

Page 37: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 37

Java’s Exception Class

Page 38: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 38

After a method throws an exception, the runtime system attempts to find something to handle it.

Page 39: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 39

The list of methods is known as the call stack

Page 40: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 40

Searching the call stack for the exception handler.

Page 41: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 41

Checked Exceptions

Any exception that can be recognized by the compiler.

Example:

FileNotFoundExceptions.

Page 42: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 42

Unchecked Exceptions 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:throws ExceptionType1, ExceptionType2,...

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

Page 43: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 43

Checked and Unchecked Exceptions

If a checked exception is thrown by a method , or if that method calls methods that throw a checked exceptions, each of those exceptions must be declared in the throws clause of that method or caught in a try/catch in that method.

Page 44: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 44

Exceptions Example Code

public static void exceptionMethod()

throws InputMismatchException,

FileNotFoundException

{

//statements

}

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

Page 45: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 45

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 46: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 46

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() + ”division by zero”); else if (eRef instanceof InputMismatchException) System.out.println("Line 16: Exception " + eRef.toString() + “invalid input”); }

Page 47: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 47

Example 12-6

Page 48: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 48

int dividend, divisor;double quotient; 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 = (double) dividend / divisor; System.out.println("Line 11: Quotient = " + quotient);

}catch (ArithmeticException aeRef) {

System.out.println("Line 13: Exception " + aeRef.toString());

}catch (InputMismatchException imeRef) {

System.out.println("Line 15: Exception " + imeRef.toString());

}}

Page 49: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 49

Sample run

Line 4: Enter the dividend: 12

Line 7: Enter the divisor: 0

Line 11: Quotient = Infinity

Page 50: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 50

public static void main (String[] args) {

int dividend, divisor; double quotient; 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 = result(dividend,divisor); System.out.println("Line 11: Quotient = " + quotient); } catch (ArithmeticException aeRef){ System.out.println("Line 13: Exception " + aeRef.toString()); }

catch (InputMismatchException imeRef) { System.out.println("Line 15: Exception " + imeRef.toString()); }}

public static double result( int number1, int number2) throws ArithmeticException

{ if (number2 == 0) throw new ArithmeticException("Attempted to divid by zero"); return (double) number1 / number2; }

Page 51: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 51

Sample run

Line 4: Enter the dividend: 12

Line 7: Enter the divisor: 0

Line 13: Exception java.lang.ArithmeticException: Attempted to divid by zero

Page 52: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 52

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 53: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 53

Rethrowing and Throwing an Exception

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.

Syntax:

throw exceptionReference;//checked or unchecked exception

Page 54: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 54

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

Page 55: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 55

public static int getNumber() { 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

Page 56: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 56

Sample Run

Line 11: Enter an integer: e

Line 7: Exception java.util.InputMismatchException

Page 57: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 57

import java.util.*;public class RethrowExceptionExmp2{ 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()); } }}

Example 12-8

Page 58: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 58

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) { System.out.println("Line16: Exception " + imeRef.toString()); throw new InputMismatchException ("getNumber"); } }}

Page 59: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 59

Sample Run

Line 11: Enter an integer: e

Line 16: Exception java.util.InputMismatchException

Line 7: Exception java.util.InputMismatchException: getNumber

Page 60: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 60

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

Page 61: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 61

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

Rethrowing and Throwing an Exception

Page 62: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 62

Sample Run

Line 11: Enter an integer: e

Line 7: Exception java.util.InputMismatchException

Page 63: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 63

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()); } }}

Page 64: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 64

public static int getNumber() { int num; try { System.out.print("Line 11: Enter an “ + "integer: "); num = console.nextInt(); System.out.println(); return num; } catch (InputMismatchException imeRef) { System.out.println("Line 7: Exception " + imeRef.toString());//this will cause a compile error even if you //define the exception using the throws clause of //the getNum method heading//compile error message: missing return statement } }}

Page 65: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 65

Rethrowing and Throwing an Exception

The mechanism of rethrowing an exception allows a program to handle all the exceptions in one location rather than spreading exception-handling code throughout the program

Page 66: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 66

The Method printStackTrace

Used to determine the order in which the methods were called and where the exception was thrown.

Page 67: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 67

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

Page 68: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 68

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

Page 69: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 69

Example 12-9

Because the methods A and B do not handle the exception thrown by methodC, they contain the throws Exception clause in their heading

Page 70: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 70

Sample Run:java.lang.Exception: Exception generated in method C

caught in mainjava.lang.Exception: Exception generated in method C at PrintStackTraceExample1.methodC - (PrintStackTraceExample1.java:31) at PrintStackTraceExample1.methodB - (PrintStackTraceExample1.java:26) at PrintStackTraceExample1.methodA - (PrintStackTraceExample1.java:22) at PrintStackTraceExample1.main - (PrintStackTraceExample1.java:11)

The Method printStackTrace

Page 71: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 71

Example 12-10

Page 72: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 72

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

Page 73: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 73

public static void methodA() throws Exception{ methodB();}public static void methodB() throws Exception{ methodC();}public static void methodC(){ throw new Exception("Exception generated in method C"); }}//this will cause a compile error:Line 30 : unreported exception java.lang.Exception; must be caught or declared to be thrown//if the exception was unchecked exception it will not cause this compile error

The Method printStackTrace

Page 74: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 74

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 75: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 75

Example 12-11

FixErrorAndContinue

Page 76: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 76

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.

Page 77: Chapter 12: Handling Exceptions and Events

Java Programming: From Problem Analysis to Program Design, Second Edition 77

Chapter Summary Exception

Hierarchy Classes

Checked and unchecked exceptions The method printStackTrace Exception handling techniques:

Terminate program. Fix error and continue. Log error and continue.