Exception handling Exception infrequent, abnormal situation in - - PowerPoint PPT Presentation

exception handling
SMART_READER_LITE
LIVE PREVIEW

Exception handling Exception infrequent, abnormal situation in - - PowerPoint PPT Presentation

Exception handling Exception infrequent, abnormal situation in program logic at program execution not necessarily an error Reasons for exceptions: hardware events arithmetic overflow, parity errors operating


slide-1
SLIDE 1

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

1

Exception handling

  • Exception

– infrequent, abnormal situation in program logic at program execution – not necessarily an error

  • Reasons for exceptions:

– hardware events

  • arithmetic overflow, parity errors

– operating system events

  • out of memory exception

– programming language properties

  • dynamic range checks

– application program properties

  • subprogram abuse, data structure overflow/underflow
slide-2
SLIDE 2

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

2

Exception handling

  • Necessary actions to continue program execution

after detecting an exception

– reporting about the exception – controlled program termination

  • Exception recovery (different choices)

– new trial

  • e.g. after restoring data structures

– alternative action – memory allocation – ask for instructions

protected block exception handler raise/throw an exception

slide-3
SLIDE 3

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

3

Tools for reporting exceptions

  • Using parameters (or global variables):
  • Using a special exceptional value:

procedure Search ( K: Key; var D: Info; var Found: Boolean ); begin ... end; ... Search ( k, d, f ); if not f then ... exception handling ... procedure Search ( K: Key; var D: Info ); begin ... end; ... Search ( k, d ); if d = NotFound then ... exception handling ...

slide-4
SLIDE 4

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

Comparison to Go

f, err := os.Open ( ”filename.txt” ) if err != nil { log.Fatal ( err ) // prints error message and stops } // do something with the open *File f func Open ( name string ) ( file *File, err error )

slide-5
SLIDE 5

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

5

Tools for giving instructions

  • Passing a label as a parameter:
  • Passing a handler routine as a parameter:

procedure Search ( K: Key; var D: Info; label NotFound ); begin ... if ...not found ... then goto NotFound; end; ... Search ( k, d, L ); // and jump over L L: ... exception handling ... procedure Search ( K: Key; var D: Info; procedure NotFound ); begin ... if ...not found ... then NotFound; end; procedure P; begin ... exception handling ... end; ... Search ( k, d, P );

slide-6
SLIDE 6

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

6

Benefits of language-provided exception handling

  • Specific concepts for exception handling

– high-level abstraction

  • Exceptional situations distinguished from the

normal program logic

– readability, understandability, (orthogonality)

  • Efficiency?

– does not burden normal program execution

  • Handling mechanism also for system exceptions
slide-7
SLIDE 7

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

7

Design issues for exception handling

  • How to detect an exception? How to handle

hardware exceptions?

  • How, when and where to report about the

exception? How to select a handler?

  • How to bind an exception and its handler

together?

– how is the handler related to the code sequence where its exceptions occur?

  • What to do after the exception is handled?
slide-8
SLIDE 8

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

8

Ada

  • Exceptions are built-in types
  • Handlers are associated statically with large program units

– blocks, subprograms, packages, tasks – handler is bound dynamically (after subprogram calling order)

  • Multi-level handling

– moving backwards in the chain of called subprograms until the suitable handler is found

  • Exception can also be raised in an exception handler

declare empty_queue: exception;

slide-9
SLIDE 9

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

9

package Stack is procedure Push ( X: Integer ); function Pop return Integer; Underflow, Overflow: exception; end Stack; package body Stack is max: constant := 10; S: array ( 1.. max ) of Integer; top: Integer range 0 .. max; procedure Push ( X: Integer ) is begin if top = max then raise Overflow; end if;

  • - actual code for Push

end Push; function Pop return Integer is ... raise Underflow; ... end Stack; declare use Stack; begin ... Push ( 3 ); ... exception when Underflow | Overflow => Put ( ”Error in stack handling” ); end;

Example on Ada exception handling Location for handler:

  • 1. Block
  • 2. Subprogram body
  • 3. Package body
  • 4. Task body
slide-10
SLIDE 10

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

10

Binding handler to an exception (Ada)

  • Moving exception (until suitable handler is found)

– from subprogram body

  • the same exceptions is raised again in the call of the

subprogram

– from block

  • the same exception is raised again after the block

– from package body

  • the same exception is raised again after the body

– from task body

  • not moved, task is terminated

– from declarations

  • elaboration of declarations is terminated
slide-11
SLIDE 11

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

11

Control flow in different situations (Ada)

procedure P is Error: exception; procedure R; procedure Q is begin R; ... -- raising Error ( 2 ) exception when Error => ... ; end Q; procedure R is begin ... – raising Error ( 3 ) end R; begin ... -- raising Error ( 1 ) Q; ... exception when Error => ... ; end P;

slide-12
SLIDE 12

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

12

Predefined exceptions (Ada)

  • Constraint_Error:

– restriction (e.g. range restriction) is broken

  • Storage_Error:

– memory exhaustion

  • Tasking_Error:

– error in tasks

  • Program_Error:

– other error occurs

slide-13
SLIDE 13

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

13

Exception handling in Eiffel

do_task is local times_tried: INTEGER do if times_tried = 0 then implementation1 elsif times_tried = 1 then implementation2 end rescue times_tried := times_tried + 1; if times_tried < 2 then ... repairing data structures ... retry end end;

slide-14
SLIDE 14

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

14

C++

  • Exception terminology:

– try-block

  • includes the error-prone code (protected block)

– throw-command

  • throws (raises) an exception

– catch-block

  • handles the exception
  • Exception

– can be a data element or object of any type – does not necessarily have a name – exception class

slide-15
SLIDE 15

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

15

C++

int space_left ( int index ) { if ( index >= MAX ) throw ( index ); else return 1; } int main ( void ) { int array [ MAX ]; int i = 0; try { while ( space_left ( i ) && ( cin >> array [ i ] ) ) i++; } catch ( int i ) { cout << ”Index ” << i << ”out of range\n”; } return 0; }

slide-16
SLIDE 16

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

16

C++ (exception class)

class OverIndex { private: int ind; public: OverIndex ( int i ) { ind = i; } void report ( ) { cout << ”Bad index: ” << ind; } }; int const SIZE = 10; int table [ SIZE ]; int InsideTable ( int i ) { if ( i >= SIZE ) throw OverIndex ( i ); else return 1; } void main ( ) { int ind; try { ind = 0; while ( InsideTable ( ind ) ) cin >> table [ ind++ ]; } catch ( OverIndex error ) { error.report ( ); } }

slide-17
SLIDE 17

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

17

C++ standard exception hierarchy

runtime_error logic_error bad_typeid bad_alloc exception invalid_argument bad_cast bad_exception range_error domain_error length_error

  • ut_of_range

underflow_error

  • verflow_error
slide-18
SLIDE 18

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

18

Java

  • Resembles C++ exception handling
  • Exeptions are instances of Throwable

– predefined exception classes: Error and Exception and their subclasses

  • Exceptions must be given in the header of an
  • peration
  • finally-clause (after try and catch blocks)

– is executed always (regardless of exceptions)

try { ... } catch { ... } // more handlers finally { ... }

slide-19
SLIDE 19

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

19

Haskell

  • Lazy evaluation -> execution order ”undefined” ->

???

  • Exceptions are problematic

– when to throw, when to catch

  • Haskell allows exceptions only in IO functions

(where order is predefined)

  • Other mechanisms must be used in the purely

functional side

slide-20
SLIDE 20

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

20

Haskell

  • Function error prints an error message and

terminates the program (its value is undefined)

  • No error handling or recovery possible!

Div1 :: Int -> Int -> Int Div1 _ 0 = error ”Division by zero” Div1 x y = div x y

slide-21
SLIDE 21

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

21

Haskell (Maybe)

  • Maybe structure contains either a value (Just x) or special

Nothing

  • Note: return type is a Maybe value, not the result of the division
  • Use of Maybe:

Div2 :: Int -> Int -> Maybe Int Div2 _ 0 = Nothing Div2 x y = Just ( div x y ) mean lst = let sum = foldr (+) 0 lst

  • - sum over list elements

nmbr = fromIntegral ( length lst )

  • - number of elements

in case ( Div2 sum nmbr ) of Nothing -> 0

  • - no values, mean set to 0

Just x -> x

  • - otherwise the Maybe value

data Maybe a = Nothing | Just a

slide-22
SLIDE 22

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

22

Haskell (Either)

  • Maybe structure does not report about an error
  • Another option: Either structure, resembles C++

union (but is safer)

  • Makes it possible to create user-defined error types
  • ”A plea for consistency… But I’d be just as happy if

we could standardize on two or three of the above whenever possible!”

− http://www.randomhacks.net/articles/2007/03/10/haskell-8- ways-to-report-errors

Div3 :: Int -> Int -> Either Int [Char] Div3 _ 0 = Left ”Division by zero” Div3 x y = Right ( div x y ) data Either a b = Left a | Right b

slide-23
SLIDE 23

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

23

Implementation of exceptions

  • How to find the handler for an exception?
  • The most obvios solution:

– stack of handlers – when program execution reaches a protected block, the handler of the block is pushed to the stack

  • if there is a handler for the block

– after the block execution, the added handler is popped from the stack – the innermost handler is always found on the top of the stack

  • Drawback:

– increases run time overhead also in the normal case

slide-24
SLIDE 24

Principles of programming languages Maarit Harsu / Matti Rintala / Henri Hansen

TUT Pervasive Computing

24

More efficient implementation for exceptions

  • Consecutive source code (block) is usually compiled into

consecutive machine code instructions

– table generated at compile time – each table entry contains two fields: starting address of code block and the corresponding handler address – table is sorted according to block addresses – upon exceptions, binary search is applied on the table, using program counter (PC) as the key

  • The cost of raising an exception is higher than in the
  • bvious solution, but there is no overhead in normal cases

block: ... ... PC→ ... → exception ... handler: ...

block address handler address block address handler address block address handler address

...