Top Banner
Exceptions Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package Revised 12/16/99
40

Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

Jan 15, 2016

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

ExceptionsExceptions

Cmput 115 - Lecture 3

Department of Computing Science

University of Alberta©Duane Szafron 1999

Some code in this lecture is based on code from the book:Java Structures by Duane A. Bailey or the companion structure package

Revised 12/16/99

Page 2: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

2

About This LectureAbout This Lecture

In this lecture we learn how to use Java Exceptions to handle unusual program conditions. Note, this material is not in the text book.

Page 3: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

3

OutlineOutline

Assertions and generic exceptions

Throwables, Errors and Exceptions

Throwing exceptions

Catching exceptions

Exception matching

User-defined Throwable classes

Multiple catch clauses and the finally clause

Page 4: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

4

Exceptions - Failed AssertionsExceptions - Failed Assertions

An assertion is a condition that should be true.

What happens if the assertion fails?

One option is to report that the assertion has failed and to halt the program. (Preventive Approach)

Alternately, the programmer can signal that an unusual event has occurred and call some code to handle the special case. (Corrective Approach)

In general, these special cases are generically called Exceptions.

Page 5: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

5

Quick ExampleQuick Example

Want to determine the number of pretzels per glass of beer

Enter number of pretzels:12Enter number of glasses of beer:5

12 pretzels5 glasses of beerWe have 2.4 pretzels for each glass of beer.

Page 6: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

6

Quick ExampleQuick Example

Want to determine the number of pretzels per glass of beer

Enter number of pretzels:13Enter number of glasses of beer:0

No Beer!Go get some at RAT’sProgram aborted.

Page 7: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

7

GotBeer GotBeer (1 of 2)(1 of 2)

Public class GotBeer{ public static void main(String[ ] args) { int beerCount, pretzelCount; double pretzelsPerGlass;

System.out.println(“Enter number of pretzels:”); pretzelCount = Savit.readLineInt( ); System.out.println(“Enter number of glasses of beer:”); beerCount = Savit.readLineInt( );

if (beerCount <= 0) { System.out.printlin(“No Beer!”); System.out.println(“Go to RAT’s”); System.out.println(“Program Aborted”); System.exit(0); }

Assert.condition(beerCount>0, “No Beer!\nGo to RAT\’s\nProgramAborted”); }

Page 8: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

8

GotBeer GotBeer (1 of 2)(1 of 2)

pretzelsPerGlass = pretzelCount/(double)beerCount;

System.out.prtintln(pretzelCount + “ pretzels.”); System.out.prtintln(beerCount + “ glasses of beer.”); System.out.prtintln(“You have “ + pretzelsPerGlass + “ pretzels for each glass of beer.”); }}

Page 9: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

9

GotBeerGotBeer with Exceptions with Exceptions (1 of 2)(1 of 2)

Public class GotBeer{ public static void main(String[ ] args) { int beerCount, pretzelCount; double pretzelsPerGlass;

try { System.out.println(“Enter number of pretzels:”); pretzelCount = Savit.readLineInt( ); System.out.println(“Enter number of glasses of beer:”); beerCount = Savit.readLineInt( );

if (beerCount <= 0) throw new Exception(“No Beer!);

Page 10: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

10

GotBeerGotBeer with Exceptionswith Exceptions (1 of 2)(1 of 2)

pretzelsPerGlass = pretzelCount/(double)beerCount;

System.out.prtintln(pretzelCount + “ pretzels.”); System.out.prtintln(beerCount + “ glasses of beer.”); System.out.prtintln(“You have “ + pretzelsPerGlass + “ pretzels for each glass of beer.”);} // End of “try” block.

Catch(Exception e) { System.out.println(e.getMessage()); //”No Beer!” System.out.println(“Go to RAT’s”); System.out.println(“Program Aborted”); System.exit(0); } } } //End of “main”

Page 11: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

11

Generic Exceptions in JavaGeneric Exceptions in Java

In Java, the generic concept of an exception is represented by a class called Throwable.

In Java, a throw statement is used to signal an unusual situation in a program.

The Java syntax is:

throw <instance of a subclass of the Throwable class>

In Java, there are two subclasses of the Throwable class, Error and Exception.

However, Java errors and exceptions are both considered exceptions in the generic sense.

Page 12: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

12

The The throwsthrows Statement Statement

A throws statement is used to signal that an generic exception (Java exception or Java error) has occurred.

The syntax of a throws statement is:

throws <throwable expression>

The <throwable expression> is any expression that evaluates to an object that is an instance of the Throwable class or any subclass.

Page 13: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

13

Throwing an ErrorThrowing an Error

An Error is used when the program should be halted.

code based on Bailey pg. 8

For example, we could modify our Ratio constructor:

public Ratio(int top, int bottom) {/* pre: bottom != 0 post: constructs a ratio equivalent to top/bottom */// Assert.pre(bottom != 0, "Denominator must not be 0");

if (bottom == 0) throw new Error(“Denominator must not be 0”);this.numerator = top;this.denominator = bottom;

}

Page 14: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

14

An Error Halts the ProgramAn Error Halts the Program

When an error is thrown, the program is haltedhalted, a message is displayed, and the stack frames are displayed:

_exceptionOccurred: java.lang.Error (Denominator must not be 0)java.lang.Error: Denominator must not be 0

at Ratio.<init>(Ratio.java)at RatioTest.main(RatioTest.java)at

com.apple.mrj.JManager.JMStaticMethodDispatcher.run(JMAWTContextImpl.java)

at java.lang.Thread.run(Thread.java)detailed

application

Page 15: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

15

ExceptionsExceptions

An Exception is used when some special code may be used to handle the exception.

Every method that throws an exception must either catch (handle) the exception or pass the exception back to calling method using a throws clause in its method signature.

When an exception is thrown, the java interpreter looks for an exception handler.

Page 16: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

16

Throwing an ExceptionThrowing an Exception

For example:

public Ratio(int top, int bottom) throws Exception {

/* pre: bottom != 0

post: constructs a ratio equivalent to top/bottom */

if (bottom == 0)

throw new Exception("Denominator must not be 0");

this.numerator = top;

this.denominator = bottom;

}

code based on Bailey pg. 8

Page 17: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

17

The The throwsthrows Clause Clause Each using method of the method that throws an exception must also either

catch the exception or have a throws clause in its signature to throw it to its caller:

public Ratio add(Ratio other) throws Exception {

/* pre: other is non-null

post: return new fraction - the sum of this and

other */

Assert.pre(other != null, "Other must not be null");

return new Ratio (this.numerator*other.denominator+

this.denominator*other.numerator,

this.denominator*other.denominator);

}

code based on Bailey pg. 8

Page 18: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

18

Chaining Chaining throwsthrows clauses clauses

public static void main(String args[]) throws Exception{

Ratio r = new Ratio(1,1); // r == 1.0

r = new Ratio(1,2); // r == 0.5

r.add(new Ratio(1,3)); // r still 0.5

r = r.add(new Ratio(1,4)); // r == 0.75

System.out.println(r.value()); // 0.75 printed

r = new Ratio(1, 0); // should be an exception

}code based on Bailey pg. 9

Eventually either the Exception must be caught or the signature of the main method must contain a throws clause:

Page 19: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

19

Exceptions not CaughtExceptions not Caught

If an exception is not caught by any handler, the exception behaves like an Error: the program is haltedhalted, a message is displayed, and the stack frames are displayed:

_exceptionOccurred: java.lang.Exception (Denominator must not be 0)java.lang.Exception: Denominator must not be 0

at Ratio.<init>(Ratio.java)at RatioTest.main(RatioTest.java)at

com.apple.mrj.JManager.JMStaticMethodDispatcher.run(JMAWTContextImpl.java)

at java.lang.Thread.run(Thread.java)

Page 20: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

20

The The try-catch-finallytry-catch-finally statement statement

A try-catch-finally statement is used to catch an exception (and therefore to prevent program termination).

The EBNF Java syntax is:

try <try block> {<catch clause>} [<finally clause>];

Recall that in Extended BNF, { } means zero or more occurrences and that [ ] means an optional occurrence.

The <try block> is just a compound statement.

Page 21: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

21

The The catchcatch clause clause

The Java syntax for a catch clause is:

catch (<exception declaration>) <catch block>

The <catch block> is just a compound statement.

The <exception declaration> declares the classes of exception that will be caught.Its syntax is:

<exception classname> <variable>

Page 22: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

22

Simple Example SyntaxSimple Example Syntax

Here is the syntax for a simple example with one catch clause and no finally clause:

try {r = new Ratio(x, y);

/* . . . more statements . . . */}catch (Exception anException) {

System.out.println(anException);r = new Ratio(); // initializes to 0/1

}

code based on Bailey pg. 9

1: If y=0 & if no catch clause, Exit

3

See slide16for wherethrowstakes place

enhanced

2y ~= 0y = 0

Page 23: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

23

Semantics for Simple try-catch Semantics for Simple try-catch 11

If an expression in the try block of a statement with one catch clause and no finally clause throws an exception:

– the rest of the code in the try block is skipped.

– If the exception “matches” the catch clause, the statements in the catch block are run, followed by the rest of the method (case 3).

– If the exception does not match the catch clause, the rest of code in the method is skipped and the exception is thrown to the calling method (case 1).

Page 24: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

24

Semantics for Simple try-catch Semantics for Simple try-catch 22

If an expression in the try block does not throw an exception (case 2):– The catch clause is skipped.– The rest of the method is run normally.

If you put a try-catch-finally statement around a method that may generate an exception, you can remove the throws clause in the calling method’s signature.(Why? ...because you are handling the exception in the method withthe Catch phrase.)

Page 25: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

25

Example: Example: try-catchtry-catch For example:

public static void main(String args[ ]) throws Exception {Ratio r;

try {r = new Ratio(1, 0);

}catch (Exception anException) {

System.out.println(anException);r = new Ratio(); // initializes to 0/1

}System.out.println(r);

}

can be removed

code based on Bailey pg. 9

java.lang.Exception: Denominator must not be 00.0(Note ... See slide 10)

Page 26: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

26

Why Use Exceptions?Why Use Exceptions?

Why not just put the exception code in the method where the exception is thrown instead of throwing the exception?

Because, different callers may want to handle the same exception differently.

For example, the previous segment binds the variable “r” to a “zero” Ratio.

A different segment might want to bind the variable “r” to null if an exception occurs.

Page 27: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

27

Exception MatchingException Matching

When does a thrown exception “match” a catch clause?

– The thrown exception has a class.

– The variable in the exception declaration of the catch clause has a declared class.

– They “match” if class of the thrown exception is the same as the declared class in the catch clause or is one of its subclasses.

Page 28: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

28

Example: Exception Matching Example: Exception Matching 11

For example if the thrown exception class is a NumberFormatException:

public Ratio(int top, int bottom) throws NumberFormatException{

/* pre: bottom != 0 post: constructs a ratio equivalent to top/bottom */ if (bottom == 0) throw new NumberFormatException( "Denominator must not be 0"); this.numerator = top; this.denominator = bottom;}

code based on Bailey pg. 8

It can be caught by a NumberFormatException or any of its superclasses:

Page 29: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

29

Example: Exception Matching 2Example: Exception Matching 2public static void main(String args[ ]) {

Ratio r;

try {r = new Ratio(1, 0);

}catch (NumberFormatException anException) {// or IllegalArgumentException or RuntimeException or// Exception

System.out.println(anException);r = new Ratio(); // initializes to 0/1

}System.out.println(r);

}

java.lang.NumberFormatException: Denominator must not be 00.0

code based on Bailey pg. 8

Page 30: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

30

Throwable Inheritance HierarchyThrowable Inheritance Hierarchy

Object

Error

Throwable

Exception

Linkage ClassNotFound Runtime

IllegalThreadState

IllegalArgument IndexOutOfBound

NumberFormat

User-Defined?

Page 31: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

31

User-defined Throwable ClassesUser-defined Throwable Classes

You can define your own Exception subclasses.

This allows you to conditionally match only the Exceptions that you want to match.

You can also define your own Error subclasses, although you cannot use them to “catch” errors.

Page 32: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

32

Example: User-defined Errors Example: User-defined Errors 11

For example, the implementation of the Assert class, uses a new error subclass:

code from Bailey structure package

static public void pre(boolean test, String message)

// pre: result of precondition test.

// post: does nothing if test true, otherwise abort w/message

{

if (test == false) throw new FailedPrecondition(message);

}

Page 33: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

33

Example: User-defined Errors Example: User-defined Errors 22

class FailedAssertion extends Error {public FailedAssertion(String reason)

// post: constructs a new failed assertion error{

super("\nAssertion that failed: " + reason);

} }

code from Bailey structure package

class FailedPrecondition extends FailedAssertion {public FailedPrecondition(String reason)// post: constructs a new failed precondition{ super("\nA precondition: " + reason);} }

overrides

Error

Failed Assertion

Failed Precondition

subclass of

subclass of

Page 34: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

34

““finally” and Multiple catches finally” and Multiple catches

You can put multiple catch clauses in the try statement to handle different kinds of exceptions in different ways.

If you want to execute some code, whether an exception was raised or not, you can use the optional finally clause.

The syntax of a finally clause is: finally <finallyBlock>

The <finallyBlock> is just a compound statement.

Page 35: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

35

Full Semantics of Full Semantics of try-catch-finallytry-catch-finally 11

If an expression in the try block throws an exception:

– the rest of the code in the try block is skipped.

– If the exception “matches” the first catch clause• the code in its catch block is run

• the optional code in the finally clause is run.

• the rest of the catch clauses are ignored.

• the rest of the code in the method is run.

Page 36: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

36

Full Semantics of Full Semantics of try-catch-finallytry-catch-finally 22

– If the exception does not “match” the first catch clause, similar actions are taken for the first “matching” catch clause.

– If the exception does not “match” any catch clause

• the optional code in the finally clause is run

• all other code in the method is abandoned

• the exception is thrown to the calling method.

Page 37: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

37

Example: finally & Multiple catches Example: finally & Multiple catches 11

public Ratio divide(Ratio other) throws Exception {

/* pre: other is non-nullpre: other is not zeropost: return new fraction - the division of this and other

*/if (other == null) throw new NullPointerException();else if (other.numerator == 0) throw new ArithmeticException();else return new Ratio(this.numerator*other.denominator, this.denominator*other.numerator);} }

code based on Bailey pg. 9

Page 38: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

38

Example: finally & Multiple catches Example: finally & Multiple catches 22

public static void main(String args[ ]) {try { UseRatio.divide(new Ratio(1, 2), new Ratio(3,4)); // should work

UseRatio.divide(new Ratio(1, 2), new Ratio(0,4)); // ArithmeticException caught in UseDivide()

UseRatio.divide(new Ratio(1, 2), null); // NullPointerException caught in UseDivide()

UseRatio.divide(null, new Ratio(3,4)); // NumberFormatException NOT caught in UseDivide()

}catch (Exception anException) { System.out.println("NumberFormatException not caught by divide()"); } }

code based on Bailey pg. 9

Page 39: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

39

Example: finally & Multiple catches Example: finally & Multiple catches 33

private static void divide(Ratio top, Ratio bottom) throws Exception

/* Compute the division of top by bottom and report the answer. If top is null then change it to an invalid ratio 1/0 to generate a NumberFormatException that won't be caught. Catch the other exceptions: bottom is zero or bottom is null. */

Ratio answer;answer = null;try { if (top == null) top = new Ratio(1, 0); //Doesn’t make sense but throws // NumberFormat Exception

answer = top.divide(bottom); } code based on Bailey pg. 9

Page 40: Exceptions Cmput 115 - Lecture 3 Department of Computing Science University of Alberta ©Duane Szafron 1999 Some code in this lecture is based on code from.

©Duane Szafron 1999

40

Example: finally & Multiple catches Example: finally & Multiple catches 44

catch (ArithmeticException anException) { System.out.println("Arithmetic Except: no div by 0"); answer = new Ratio(); }

catch (NullPointerException anException) { System.out.println("NullPointerExcept: no div by null"); answer = new Ratio(); }

finally { System.out.println("Finally the answer: " + answer); }

// rest skipped for NumberFormat Exception since not caughtSystem.out.println("End method answer: ” + answer.value());

}

code based on Bailey pg. 9