Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail...

34
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department of Computer Science and Software Engineering

Transcript of Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail...

Page 1: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Slides prepared by Rose Williams, Binghamton University

ICS201

Exception Handling

University of Hail

College of Computer Science and Engineering

Department of Computer Science and Software Engineering

Page 2: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

What is an Exception?Indication of problem during

execution

Examples

– Divide by zero errors

– Accessing the elements of an array outside its range

– Invalid input

– Opening a non-existent file

– …

Page 3: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Exception Handling in Java 3

Exceptions– a better error handling

Exceptions act similar to method return

flags in that encounter an error.

Exceptions act like global error methods

in that the exception mechanism is built

into Java

Page 4: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Exception Exampleclass DivByZero {public static void main(String args[]) { System.out.println(3/0); System.out.println(" Pls. print me. "); } }Displays this error messageException in thread "main"java.lang.ArithmeticException: / by zeroat DivByZero.main(DivByZero.java:3)

Causes the program to terminate

Page 5: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Another Examplepublic class ExceptionExample {

public static void main(String args[]) {

String[] greek = {"Alpha","Beta"};

System.out.println(greek[2]);

}

}

Output:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4)

Page 6: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Exception Handling in Java 6

Coding ExceptionsTo handle the exception, you write a “try-

catch” block.

try {… normal program code}catch(Exception e) {… exception handling code}

It prevents the program from automatically terminating

Page 7: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

7

Example

Output:Division by zero.

After catch statement.

Page 8: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

public class ExceptionExample {

public static void main(String args[]) {

try{

String[] greek = {"Alpha","Beta"};

System.out.println(greek[2]);

}

catch(Exception e)

{

System.out.print ("Index of array out of range");

}

}

}

Page 9: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Catching Multiple ExceptionsHandle multiple possible

exceptions by multiple successive catch blocks

try { // code that might throw multiple exception

}

catch (IOException e) {

// handle IOException and all subclasses

}

catch (ClassNotFoundException e2) {

// handle ClassNotFoundException

}

Page 10: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

10

Exception Handler

Exception "thrown"

here

Exception handler

Exception handler

Thrown exception matched against first set of exception

handlers

Thrown exception matched against first set of exception

handlers

If it fails to match, it is matched against next set of handlers, etc.

If it fails to match, it is matched against next set of handlers, etc.

If exception matches none of handlers, program is discarded

If exception matches none of handlers, program is discarded

Page 11: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Exception Classes

There are two kinds of exceptions in Java

Predefined exception classes in the Java

libraries

New exception classes can be defined like any other

class

Page 12: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Exception Classes from Standard Packages

Predefined exception classes are included in the standard packages that come with Java◦ For example:IOExceptionNoSuchMethodExceptionFileNotFoundException

◦ Many exception classes must be imported in order to use themimport java.io.IOException;

All predefined exception classes have the following properties:◦ There is a constructor that takes a single argument of

type String◦ The class has an accessor method getMessage that can

recover the string given as an argument to the constructor when the exception object was created.

Page 13: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Exception Classes from Standard Packages

The predefined exception class Exception is the root class for all exceptions

◦ Every exception class is a derived class of the class Exception

◦ Although the Exception class can be used directly in a class or program, it is most often used to define a derived class

◦ The class Exception is in the java.lang package, and so requires no import statement

9-13

Page 14: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

A Programmer-Defined Exception Class

Page 15: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

15

Types of error:

1. Syntax errors: the rules of the language have

not been followed (detected by the compiler).

2. Runtime errors occur while the program is

running (detects an operation that is

impossible to carry out).

3. Logic errors occur when a program doesn't

perform the way it was intended to.

Page 16: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

16

Runtime Errors

import java.util.Scanner; public class ExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); } }

If an exception occurs on this line, the rest of the lines in the method are skipped and the program is terminated.

Terminated.

Page 17: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

17

Catch Runtime Errors

import java.util.*; public class HandleExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in);

boolean continueInput = true;

do { try { System.out.print("Enter an integer: "); int number = scanner.nextInt(); // Display the result System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException e) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); scanner.nextLine(); // discard input } } while (continueInput); } }

If an exception occurs on this line, the rest of lines in the try block are skipped and the control is transferred to the catch block.

Page 18: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

18

Throwing Exceptions

When the program detects an error, the program can create an instance of an exception type and throw it. This is known as throwing an exception.

Page 19: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

19

Using the throws ClauseAppears after method’s parameter list and before

the method’s bodyContains a comma-separated list of exceptionsExceptions can be thrown by statements in

method’s body of by methods called in method’s body

Exceptions can be of types listed in throws clause or subclasses

Page 20: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

20

Declaring, Throwing, and Catching Exceptions

method1() { try { invoke method2; } catch (Exception ex) { Process exception; } }

method2() throws Exception { if (an error occurs) { throw new Exception(); } }

catch exception throw exception

declare exception

Page 21: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

21

Declaring Exceptions

Every method state the types of checked exceptions it might throw.

public void myMethod() throws IOException

public void myMethod() throws IOException, OtherException

Page 22: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

22

Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

Page 23: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

23

Sequence of Events for throw

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

Page 24: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

24

Sequence of Events for No throw

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

Page 25: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

25

1 // Fig. 13.2: DivideByZeroWithExceptionHandling.java

2 // An exception-handling example that checks for divide-by-zero.

3 import java.util.InputMismatchException;

4 import java.util.Scanner;

5

6 public class DivideByZeroWithExceptionHandling

7 {

8 // demonstrates throwing an exception when a divide-by-zero occurs

9 public static int quotient( int numerator, int denominator )

10 throws ArithmeticException

11 {

12 return numerator / denominator; // possible division by zero

13 } // end method quotient

14

15 public static void main( String args[] )

16 {

17 Scanner scanner = new Scanner( System.in ); // scanner for input

18 boolean continueLoop = true; // determines if more input is needed

19

20 do

21 {

22 try // read two numbers and calculate quotient

23 {

24 System.out.print( "Please enter an integer numerator: " );

25 int numerator = scanner.nextInt();

26 System.out.print( "Please enter an integer denominator: " );

27 int denominator = scanner.nextInt();

28

throws clause specifies that method quotient may

throw an ArithmeticException

Repetition statement loops until try block completes

successfully

try block attempts to read input and perform division

Retrieve input; InputMismatchException thrown if input not valid

integers

Page 26: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

26

29 int result = quotient( numerator, denominator );

30 System.out.printf( "\nResult: %d / %d = %d\n", numerator,

31 denominator, result );

32 continueLoop = false; // input successful; end looping

33 } // end try

34 catch ( InputMismatchException inputMismatchException )

35 {

36 System.err.printf( "\nException: %s\n",

37 inputMismatchException );

38 scanner.nextLine(); // discard input so user can try again

39 System.out.println(

40 "You must enter integers. Please try again.\n" );

41 } // end catch

42 catch ( ArithmeticException arithmeticException )

43 {

44 System.err.printf( "\nException: %s\n", arithmeticException );

45 System.out.println(

46 "Zero is an invalid denominator. Please try again.\n" );

47 } // end catch

48 } while ( continueLoop ); // end do...while

49 } // end main

50 } // end class DivideByZeroWithExceptionHandling

Call method quotient, which may throw

ArithmeticExceptionIf we have reached this point,

input was valid and denominator was non-zero,

so looping can stopCatching InputMismatchException (user has entered non-integer input)

Read invalid input but do nothing with it

Exception parameters

Notify user of error made

Catching ArithmeticException (user has entered zero for denominator)

If line 32 was never successfully reached, loop continues and user can try again

Page 27: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

27

The finally Clause

try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }

This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code.

Page 28: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

28

Sequence of Events for finally clause

Preceding step

try block

throw statement

unmatched catch

matching catch

unmatched catch

next step

finally

Page 29: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

29

Trace a Program Execution

try { statements;}catch(TheException ex) {

handling ex; }finally { finalStatements; }

Next statement;

Suppose no exceptions in the

statements

Page 30: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

30

Trace a Program Execution

try { statements;}catch(TheException ex) {

handling ex; }finally { finalStatements; }

Next statement;

The final block is always executed

Page 31: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

31

Trace a Program Execution

try { statements;}catch(TheException ex) {

handling ex; }finally { finalStatements; }

Next statement;

Next statement in the method is

executed

Page 32: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

32

Trace a Program Execution

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

Suppose an exception of type Exception1 is thrown in statement2

Page 33: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

33

Trace a Program Execution

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The exception is handled.

Page 34: Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

34

Trace a Program Execution

try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }

Next statement;

The final block is always executed.