Top Banner
ICS 313: Programming Language Theory Chapter 14: Exceptions
24
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: ICS 313: Programming Language Theory Chapter 14: Exceptions.

ICS 313:Programming Language

TheoryChapter 14: Exceptions

Page 2: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Exceptions Any unusual event that may require special processing•erroneous or not erroneous•detectable by hardware or software

Examples•Divide by zero•End of file•Array subscript out of bounds•Invalid input format•Problem-specific situation

Page 3: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Design Your Own Handling Programmers can implement some exception handling with existing programming mechanisms•Pass an extra parameter that signals status. Caller checks it on return and handles errors (C libraries)

•Pass a label parameter. Called program will GOTO that label in case of error (FORTRAN)

•Pass an exception handler subprogram as a parameter

Page 4: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Why not design your own Clutters your code•Testing for various exceptional situations

•Testing status variables on return•Passing various labels or handlers (may require many extra arguments)

Does not handle all exceptions•Duplicating (to prevent) hardware and operating system level checks

•May be asynchronous

Page 5: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Advantages of Language Support for Exceptions

More modular code•Exception handling code is placed in separate program units

•Dispatching to appropriate exception is automatic

•Can inherit handlers from dynamic or static context

Helps encourage programmers to think of possible events and handle them

Supports event-driven handling of unusual but nonerronous situations

Page 6: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Design Issues I What kind of unit is a handler? •Complete program unit, or embedded code

Where placed? •In same unit that raises the exception•Separate syntactic unit

How are relevant values communicated? •Taken from same scope (if embedded)•Passed as parameters

Page 7: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Design Issues II How are exceptions bound to handlers? •All exceptions of a given type go to one handler

•Specified by code•Inherited from superordinate unit

Is this binding static or dynamic? What happens after handling?•Program terminates•Execution continues

-At specified statement-In caller of excepted unit

Page 8: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Design Issues III Are hardware-detected errors exceptions?

Are there built in exceptions? •Are handlers predefined, or must users define them?

•Can users raise built in exceptions?•Can users redefine predefined handlers?

Are there user-defined exceptions? •How are they declared?

Can exceptions be disabled?

Page 9: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Early Approaches Program termination with core dump FORTRAN: •Branching on language-defined exceptionsREAD(UNIT=5, FMT=1000, ERR=200, END=100) DATA

PL/I•Also had language-defined exceptions•First user-defined handlers•First user-defined exceptions•Powerful, flexible, •but what a mess (too complex)

Page 10: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Improvements CLU had a more constrained approach Ada’s exception handling is based on PL/I and CLU •Scope of exceptions is program unit or block

•Static binding, but traces dynamic ancestors

•Termination of unit raising exception was required

•Could disable checking •The only show in town for many years

Page 11: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Exception Handling in C++Introduced some familiar constructss: try provides syntactic indication of scopecatch defines handlersthrow raises exceptions

Binding done by matching type of thrown object to parameters of catch

short int eof_condition; try { … throw eof_condition; … catch (short int) { … } }

short int need not have anything to do with exception!

Page 12: ICS 313: Programming Language Theory Chapter 14: Exceptions.

More on C++ Exceptions Search enclosing blocks and callers for match

Control continues after end of try of handler used

Users cannot handle system defined errors

Cannot disable exception handling No declaration of user defined exceptions is required, and exceptions are not named•(You can use classes to simulate this)

Bizarre use of type system! We can improve on this …

Page 13: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Java Exception ClassesObject

Throwable

Error Exception

RuntimeException User Defined

Errors and Runtime Exceptions: Thrown by system, Unchecked

Other Exceptions: Checked

Page 14: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Java Exception Handling try {

statement*}// zero or more of thesecatch (exceptionClass1 identifier) {

statement*, e.g., identifier.printStackTrace()}// zero or one of these finally {

statement*, e.g., closing open files}

Page 15: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Throwing Your Own in Javaclass MyException extends Exception {public MyException(String s){

super(s); }}

public void myMethod() throws MyException { // … code …throw new MyException(“Indigestible”);

}

class MyRTException extends RuntimeException not recommended by some

Page 16: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Checked Exceptions Methods must declare all checked exceptions thrown•Can tell from header which may be thrown•Overriding methods cannot add exceptions, but may remove exceptions

Callers must “deal with” checked exceptions of methods they call in one of these ways •Catch and handle: not needed in throws clause

•Catch and throw a different exception declared in throws clause

•Don’t handle: must declare in throws clause Static enforcement of this by compiler leads to safer programs

Page 17: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Unchecked Exceptions Thrown by system. Two types: Errors

•Example: out of heap memory•Fatal: Don’t catch

RuntimeException•Examples: Null pointer, array out of bounds•Can catch and handle•So ubiquitous that they are not worth checking (any code can cause it; generally a programming error)

Some Authors Differ•“use when in your judgment it is not worth forcing the client programmer to handle the exception”

Page 18: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Miscellanous Java Comments

Users can catch and handle system exceptions

Can catch all exceptions with Exception class

No default exception handlers Cannot disable exception handling Search for matching catch climbs enclosing blocks and calling methods, terminating at main

Can catch and rethrow same or different exception

Page 19: ICS 313: Programming Language Theory Chapter 14: Exceptions.

More Extensive Example PostfixCalc …

Page 20: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Evaluation of Java Exceptions

Considered an improvement over C++•Java exceptions are explicit objects, not confused with other types

•Java exceptions thrown are declared in headers while C++ programs can throw methods they don’t declare

•Unlike C++, Java run time system throws useful exceptions, and user can handle them

Comparable to Ada facilities but syntactically more modern and readable

Page 21: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Python Exceptions Exceptions are in an object hierarchy try/except similar to Java try/catch

while 1: try: x = int(raw_input("Please enter a number: ")) break except ValueError: print "Oops! That was no valid number. Try again..."

else is executed when no exceptions are raised (not the same as finally)

for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close()

Page 22: ICS 313: Programming Language Theory Chapter 14: Exceptions.

More Python Exceptions Exceptions can take arguments, be rethrown …try: f = open('myfile.txt') s = f.readline() i = int(string.strip(s))except IOError, (errno, strerror): print "I/O error(%s): %s" % (errno, strerror)except ValueError: print "Could not convert data to an integer."except: print "Unexpected error:", sys.exc_info()[0] raise

Users can define exceptions See examples in http://www.python.org/doc/current/tut/node10.html

Page 23: ICS 313: Programming Language Theory Chapter 14: Exceptions.

Prolog catch/3 and throw/1

thrower(0) :- throw(zeroException).thrower(N) :- write(N).handler :- write(zeroException).

In interpreter ...?- thrower(4).4Yes?- thrower(0).ERROR: Unhandled exception: zeroException?- catch(thrower(0), zeroException, handler).zeroExceptionYes

Without exceptions catch is like call/1 Thrown exception must unify with catcher form

Page 24: ICS 313: Programming Language Theory Chapter 14: Exceptions.

End