Eiffel: Analysis, Design and Programming. ETH Zurich, September-December Exception handling

Similar documents
Assertions, pre/postconditions

References: internet notes; Bertrand Meyer, Object-Oriented Software Construction; 10/14/2004 1

Design by Contract in Eiffel

Assertions. Assertions - Example

The Dependent Delegate Dilemma

Universe Type System for Eiffel. Annetta Schaad

Assignment 4: Object creation

Object Oriented Program Correctness with OOSimL

The Contract Pattern. Design by contract

Automated Fixing of Programs with Contracts

a correct statement? You need to know what the statement is supposed to do.

Software Architecture Bertrand Meyer. Lecture 3: Language constructs for modularity and information hiding

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

The Eiffel language. Slides partly based on :

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Readability [Skrien 4.0] Programs must be written for people to read, and only incidentally for machines to execute.

n Specifying what each method does q Specify it in a comment before method's header n Precondition q Caller obligation n Postcondition

Designing Robust Classes

Exceptions and assertions

Program Correctness and Efficiency. Chapter 2

JAVA BASICS II. Example: FIFO

CSE wi Midterm Exam 2/8/18. Name UW ID #

Design by Contract: An Overview

3. Design by Contract

Exceptions and Error Handling

Chapter 14. Exception Handling and Event Handling

Einführung in die Programmierung Introduction to Programming

Introduction to Eiffel

CSE 331 Software Design & Implementation

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

1. Quality issues (5 points)

CSE331 Winter 2014, Midterm Examination February 12, 2014

Lecture 8: Control Structures I

Java: advanced object-oriented features

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout

UC Santa Barbara. CS189A - Capstone. Christopher Kruegel Department of Computer Science UC Santa Barbara

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

CSE wi Midterm Exam 2/8/18 Sample Solution

CSE 331 Midterm Exam Sample Solution 2/13/12

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Design By Contract Deontic Design Language for Component-Based Systems

Exceptions, Case Study-Exception handling in C++.

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Softwaretechnik. Lecture 08: Testing and Debugging Overview. Peter Thiemann SS University of Freiburg, Germany

CSE 331 Midterm Exam Sample Solution 2/18/15

Lecture 10 Design by Contract

Java Loose Ends. 11 December 2017 OSU CSE 1

Einführung in die Programmierung Introduction to Programming

Softwaretechnik. Lecture 08: Testing and Debugging Overview. Peter Thiemann SS University of Freiburg, Germany

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Exception-Handling Overview

Wrapping a complex C++ library for Eiffel. FINAL REPORT July 1 st, 2005

CPSC 427: Object-Oriented Programming

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Einführung in die Programmierung Introduction to Programming

Object-Oriented Software Construction

Nature abhors a void. Bertrand Meyer. Software Engineering

Program Verification (6EC version only)

Exceptions. Gunnar Gotshalks EX 1

Mock exam 1. ETH Zurich. Date: 9./10. November 2009

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

High Quality Java Code: Contracts & Assertions

Software Architecture 4. July 2005

A comparative study of Programming by Contract and Programming with Exceptions

Principles of Programming Languages

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012

Informatica 3. Marcello Restelli. Laurea in Ingegneria Informatica Politecnico di Milano 9/15/07 10/29/07

Chapter 14. Exception Handling and Event Handling ISBN

Classes, interfaces, & documentation. Review of basic building blocks

In-Class Exercises. ETH Zurich. ETH students recently designed a special kind of oven for cooking potatoes. Here are some facts about such an oven:

Chapter 14. Exception Handling and Event Handling 异常处理和事件处理. 孟小亮 Xiaoliang MENG, 答疑 ISBN

Violations of the contract are exceptions, and are usually handled by special language constructs. Design by contract

What This Course Is About Design-by-Contract (DbC)

Defense Technical Information Center Compilation Part Notice

Regression testing. Whenever you find a bug. Why is this a good idea?

Software Architecture. Abstract Data Types

G Programming Languages - Fall 2012

Data Structures. Subodh Kumar. Dept of Computer Sc. & Engg. IIT Delhi

CSE 331 Midterm Exam 2/13/12

CMSC 631 Program Analysis and Understanding. Dynamic Typing, Contracts, and Gradual Typing

Chapter 4 Defining Classes I

Guided Random-Based Testing Strategies Diploma Thesis

Steps for project success. git status. Milestones. Deliverables. Homework 1 submitted Homework 2 will be posted October 26.

Programming II (CS300)

4.3 FURTHER PROGRAMMING

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

CS 3 Introduction to Software Engineering. 3: Exceptions

Programming with Contracts. Juan Pablo Galeotti, Alessandra Gorla Saarland University, Germany

Basics of Java: Expressions & Statements. Nathaniel Osgood CMPT 858 February 15, 2011

Chapter 3. Describing Syntax and Semantics

Chapter 3 (part 3) Describing Syntax and Semantics

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout

Programming Languages. Benjamin J. Keller Department of Computer Science, Virginia Tech

MSO Lecture Design by Contract"

Einführung in die Programmierung Introduction to Programming

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

ESC/Java2 Warnings David Cok, Joe Kiniry, and Erik Poll Eastman Kodak Company, University College Dublin, and Radboud University Nijmegen

JOURNAL OF OBJECT TECHNOLOGY

In-Class Exercises. ETH Zurich. November

The architecture of Eiffel software 3.1 OVERVIEW classes clusters systems

Transcription:

Eiffel: Analysis, Design and Programming ETH Zurich, September-December 2008-6- 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

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

Dealing with erroneous cases Calling a.f (y ) with f (x : T ) require x.pre do ensure Result.pre Normal way (a priori scheme) is either: 1. if y.pre then a.f (y ) else Error case 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.

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 Does b=? 4 this Normal program or compile Exception? in C#?

Example: Return and finally Return 2

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

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 ensure op 1 op 2... op i... op n...

Not going according to plan r (...) require... do ensure op 1 op 2... op i... op n... 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 r0 Routine call r1 r2 r3 r4

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

If no exception clause (1) Absence of a rescue clause is equivalent, in a first approximation, to an empty rescue clause: f (...) do... is an abbreviation for f (...) do rescue... -- Nothing here (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 local do rescue -- Max_attempts attempts. failures : INTEGER unsafe_transmit (message) failures := failures + 1 if failures < Max_attempts then retry

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 rescue failures := failures + 1 retry

Another Ada textbook example procedure attempt is begin <<Start>> -- 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; main; In Eiffel attempt local even: BOOLEAN do if even then algorithm_2 else algorithm_1 rescue even := not even Retry

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 rescue division_tried := True Retry

Transmitting over an unreliable line (3) 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 failed := true

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

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 s 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 ) -- Transmit message in at most Max_tries attempts. local failures : INTEGER do unsafe_transmit (message) rescue failures := failures + 1 Retry := (failures < Max_tries)

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

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 rescue division_tried := True Retry := True

The correctness of a class create a.make ( ) S1 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 } S2 S3 S4 a.f ( ) a.g ( ) a.f ( )

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... is an abbreviation for f (...) do... rescue default_rescue 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 Retry invariant P P {INV P } b {INV Q Q } {Q } r {INV (Retry P ) ( Retry R ) INV R } {INV P } do b rescue r {INV Q INV R } Normal postcondition Error postcondition

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 Bertrand Meyer: Eiffel: The Language http://se.inf.ethz.ch/~meyer/ongoing/etl/ Chapter 26: Exception handling