-5- Exception handling What is an exception? “An abnormal event” Not a very precise definition Informally: something that you don’t want to happen.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Ceg860(Prasad)L10DC1 Design by Contract Invariants Pre-post conditions : Rights and Obligations Exceptions : Contract Violations.
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Control Structures Ranga Rodrigo. Control Structures in Brief C++ or JavaEiffel if-elseif-elseif-else-end caseinspect for, while, do-whilefrom-until-loop-end.
Chair of Software Engineering OOSC - Lecture 23 1 Object-Oriented Software Construction Bertrand Meyer.
Chair of Software Engineering OOSC - Summer Semester Object-Oriented Software Construction Bertrand Meyer.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Chair of Software Engineering Software Architecture Prof. Dr. Bertrand Meyer Lecture 6: Exception Handling.
1 Design by Contract Building Reliable Software. 2 Software Correctness Correctness is a relative notion  A program is correct with respect to its specification.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
Chair of Software Engineering ATOT - Lecture 25, 30 June Advanced Topics in Object Technology Bertrand Meyer.
Chair of Software Engineering OOSC - Summer Semester Object-Oriented Software Construction Bertrand Meyer Lecture 15: Exception handling.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 18 Program Correctness To treat programming.
Exceptions (Large parts of these copied from Ed Schonberg’s slides)
Chair of Software Engineering ATOT - Lecture 12, 12 May Advanced Topics in Object Technology Bertrand Meyer.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Lecture 6: Object Creation.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Concurrency - 1 Exceptions General mechanism for handling abnormal conditions Predefined exceptions: constraint violations, I/O errors, communication errors,
Chair of Software Engineering Concurrent Object-Oriented Programming Prof. Dr. Bertrand Meyer Lecture 9: Contracts and Inheritance (based on work with.
Chair of Software Engineering Einführung in die Programmierung Introduction to Programming Prof. Dr. Bertrand Meyer Lecture 6: Object Creation.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Eiffel Language and Design by Contract Contract –An agreement between the client and the supplier Characteristics –Expects some benefits and is prepared.
1 © Wolfgang Pelz Design by Contract Design by Contract™ Based on material drawn from: Bertrand.
Ranga Rodrigo. Class is central to object oriented programming.
PRAGMATIC PARANOIA Steven Hadfield & Anthony Rice.
PZ11A Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ11A - Exception handling Programming Language Design.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Exceptions and assertions CSE 331 University of Washington.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Design by Contract Ranga Rodrigo based on Mark Priestley's Lectures.
Exceptions and Assertions Chapter 15 – CSCI 1302.
L13: Design by Contract Definition Reliability Correctness Pre- and post-condition Asserts and Exceptions Weak & Strong Conditions Class invariants Conditions.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
DBC NOTES. Design By Contract l A contract carries mutual obligations and benefits. l The client should only call a routine when the routine’s pre-condition.
Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann.
1 Exceptions When the Contract is Broken. 2 Definitions A routine call succeeds if it terminates its execution in a state satisfying its contract A routine.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
1 Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
© Bertrand Meyer and Yishai Feldman Notice Some of the material is taken from Object-Oriented Software Construction, 2nd edition, by Bertrand Meyer (Prentice.
1 ָ נן oop uException-Handling Mechanism – similar to C++ l throw e signals the occurrence of an exception lThe statement try/catch allows the calling.
Exceptions in the Java programming language J. W. Rider.
Eighth Lecture Exception Handling in Java
PZ11A Programming Language design and Implementation -4th Edition
Exception Handling and Event Handling
Design by contract Object-Oriented Software Construction by Bertrand Meyer, Prentice Hall The presence of a precondition or postcondition in a routine.
Effective Java, 3rd Edition Chapter 10: Exceptions
Design by contract Object-Oriented Software Construction by Bertrand Meyer, Prentice Hall The presence of a precondition or postcondition in a routine.
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Assertions References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 4/25/2019.
SWE 619 Last modified Fall 2007 Saket Kaushik, Paul Ammann
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
CMSC 202 Exceptions.
Exception Handling.
Programming Languages 2nd edition Tucker and Noonan
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Exception handling Programming Language Design and Implementation (4th Edition) by T. Pratt and M. Zelkowitz Prentice Hall, 2001 Section 11.1.
Design by Contract – Exceptions
Presentation transcript:

-5- Exception handling

What is an exception? “An abnormal event” Not a very precise definition Informally: something that you don’t want to happen

Exception vocabulary  “Raise”, “trigger” or “throw” an exception  “Handle” or “catch” an exception

How to use exceptions? Two opposite styles:  Exceptions as a control structure: Use an exception to handle all cases other than the most favorable ones (e.g. a key not found in a hash table triggers an exception)  Exceptions as a technique of last resort

(From an Ada textbook) sqrt (x : REAL) return REAL is begin if x < 0.0 then raise Negative ; else normal_square_root_computation ; end exception when Negative => put ("Negative argument"); return; when others =>  end; -- sqrt How not to do it

Dealing with erroneous cases Calling a. f (y ) with f (x : T ) require x. pre do … ensure Result. pre end Normal way (a priori scheme) is either: 1. if y. pre then a. f (y ) else …Error case… end 2. ensure_pre ; a. f (y)

A posteriori scheme a. try_to_invert (b) if a. could_invert then x := a. inverted else  Error case  end.

C++, Java, C#: raising programmer-defined exception Instruction: throw my_exception; try … catch (Exception e) … try … finally … The enclosing routine should be of the form my_routine (…) throws my_exception { … if abnormal_condition throw my_exception; } The calling routine must handle the exception (even if the handling code does nothing).

How not to do it: Java b= ? Normal or Exception? b= 4 Normal Does this program compile in C#?

Example: Return and finally Return 2

Example: Return and finally return= ? return=1 b=? b=2

Checked vs unchecked exceptions Checked: raised by program, caller must handle Unchecked: usually raised by external sources, don’t have to be handled

Exception handling: another approach Introduce notion of contract The need for exceptions arises when a contract is broken by either of its parties (client, supplier) Two concepts:  Failure: a routine, or other operation, is unable to fulfill its contract.  Exception: an undesirable event occurs during the execution of a routine — as a result of the failure of some operation called by the routine.

The original strategy r (...) require... do op 1 op 2... op i... op n ensure... end

Not going according to plan r (...) require... do op 1 op 2... op i... op n ensure... end Fails, triggering an exception in r (r is recipient of exception).

Causes of exceptions in O-O programming Four major kinds:  Operating system signal: arithmetic overflow, no more memory, interrupt...  Assertion violation (if contracts are being monitored)  Void call (x.f with no object attached to x)  Programmer-triggered Not any more in Eiffel & Spec#

Handling exceptions properly Exception handling principle There are only two acceptable ways to react for the recipient of an exception:  Failure: Concede impossibility of fulfilling contract, and trigger an exception in the caller (also called Organized Panic).  Retry: Try again, using a different strategy (or repeating the same one) (Rare third case: false alarm)

The call chain r0r0 r1r1 r2r2 r3r3 r4r4 Routine call

Exception mechanism Two constructs:  A routine may contain a rescue clause.  A rescue clause may contain a retry instruction. A rescue clause that does not execute a retry leads to failure of the routine (this is the organized panic case).

Exception mechanism (2) f (...) require precondition local … local entity declarations… do body ensure postcondition rescue rescue_clause end

If no exception clause (1) Absence of a rescue clause is equivalent, in a first approximation, to an empty rescue clause: f (...) do... end is an abbreviation for f (...) do... rescue -- Nothing here end (This is a provisional rule; see next.)

Transmitting over an unreliable line (1) Max_attempts : INTEGER is 100 attempt_transmission (message : STRING) is -- Transmit message in at most -- Max_attempts attempts. local failures : INTEGER do unsafe_transmit (message) rescue failures := failures + 1 if failures < Max_attempts then retryend

Transmitting over an unreliable line (2) Max_attempts : INTEGER is 100 failed : BOOLEAN attempt_transmission (message: STRING) is -- Try to transmit message; -- if impossible in at most Max_attempts -- attempts, set failed to true. local failures: INTEGER do if failures < Max_attempts then unsafe_transmit (message) else failed := True end rescue failures := failures + 1 retry end

Another Ada textbook example procedure attempt is begin > -- Start is a label loop begin algorithm_1; exit; -- Alg. 1 success exception when others => begin algorithm_2; exit; -- Alg. 2 success exception when others => goto Start; end end main; attempt local even: BOOLEAN do if even then algorithm_2 else algorithm_1 end rescue even := not even Retry end In Eiffel

Dealing with arithmetic overflow quasi_inverse (x: REAL): REAL -- 1/x if possible, otherwise 0 local division_tried: BOOLEAN do if not division_tried then Result := 1/x end rescue division_tried := True Retry end

Max_attempts: INTEGER is 100 failed : BOOLEAN attempt_transmission (message: STRING) is -- Transmit message in at most -- Max_attempts attempts. local failures: INTEGER do unsafe_transmit (message) rescue failures := failures + 1 if failures < Max_attempts then retry end failed := true … end Transmitting over an unreliable line (3)

from unsafe_transmit (message) until not exceptions loop failures := failures + 1 if failures < Max_attempts then continue l end failed := true … raise exception l: unsafe_transmit (message) end Retry allows to transfer control flow to the beginning of a routine without executing the rest of the rescue block Pseudo code

ETL3: Exception mechanism Two constructs:  A routine may contain a rescue clause  A rescue clause may set the Retry boolean variable A rescue clause that ends with Retry not set leads to failure of the routine (“organized panic”).

ETL3:Transmitting over an unreliable line (1) Max_tries : INTEGER = 100 attempt_transmission_1 (message : STRING ) local failures : INTEGER do unsafe_transmit (message) rescue failures := failures + 1 Retry := (failures < Max_tries) end -- Transmit message in at most Max_tries attempts.

ETL3: Transmitting over an unreliable line (2) Max_tries : INTEGER = 100 attempt_transmission_2 (message : STRING ) local failures : INTEGER do rescue Retry := True end -- Try to transmit message in at most Max_tries -- attempts; if impossible, set could_not to True. ; could_not:BOOLEAN if failures < Max_tries then unsafe_transmit (message) else could_not := True end

ETL3: Dealing with arithmetic overflow quasi_inverse (x: REAL): REAL -- 1/x if possible, otherwise 0 local division_tried: BOOLEAN do if not division_tried then Result := 1/x end rescue division_tried := True Retry := True end

The correctness of a class For every exported routine r : {INV and Pre r } do r {INV and Post r } For every creation procedure cp : {Pre cp } do cp {INV and Post cp } a.f (…) a.g (…) a.f (…) create a.make (…) S1 S2 S3 S4

Exception correctness For the normal body: {INV and Pre r } do r {INV and Post r } For the exception clause: {??? } rescue r {??? }

Exception correctness For the normal body: {INV and Pre r } do r {INV and Post r } For the exception clause: {True } rescue r {INV }

If no exception clause (2) Absence of a rescue clause is equivalent to a default rescue clause: f (...) do... end is an abbreviation for f (...) do... rescue default_rescue end The task of default_rescue is to restore the invariant.

For finer-grain exception handling Exceptions are objects Library mechanisms to raise exceptions, distinguish between exception types, and access details of an exception

The full rule {Q’} r {INV  (Retry  P )  (  Retry  R ) | INV  R } P  PP  P ___________________________________________ {INV  P } do b rescue r end {INV  Q Error postcondition Normal postcondition “Retry invariant” | Q’ {INV  P } b {INV  Q } } | INV  R ‘ ‘ ‘

Summary and conclusion Exceptions as a control structure (internally triggered): Benefits are dubious at best An exception mechanism is needed for unexpected external events Need precise methodology; must define what is “normal” and “abnormal”. Key notion is “contract”. Next challenge is concurrency & distribution

Further reading Bertrand Meyer: Object-Oriented Software Construction, 2nd edition, Prentice Hall, 1997 Chapter 12: When the contract is broken: exception handling ECMA-367 Standard, Section 8.26