1 / 24

ICS 313: Programming Language Theory

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

sroark
Download Presentation

ICS 313: Programming Language Theory

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  7. 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

  8. 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?

  9. Early Approaches • Program termination with core dump • FORTRAN: • Branching on language-defined exceptions READ(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)

  10. 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

  11. Exception Handling in C++ Introduced some familiar constructss: try provides syntactic indication of scope catch defines handlers throw 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!

  12. 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 …

  13. Java Exception Classes Object Throwable Error Exception RuntimeException User Defined Errors and Runtime Exceptions: Thrown by system, Unchecked Other Exceptions: Checked

  14. Java Exception Handling try { statement* } // zero or more of these catch (exceptionClass1 identifier) { statement*, e.g.,identifier.printStackTrace() } // zero or one of these finally { statement*, e.g., closing open files }

  15. Throwing Your Own in Java class MyException extends Exception { public MyException(String s){ super(s); } } public void myMethod() throws MyException { // … code … throw new MyException(“Indigestible”); } class MyRTException extends RuntimeExceptionnot recommended by some

  16. 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

  17. 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”

  18. 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

  19. More Extensive Example • PostfixCalc …

  20. 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

  21. 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()

  22. 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

  23. Prolog • catch/3 and throw/1 thrower(0) :- throw(zeroException). thrower(N) :- write(N). handler :- write(zeroException). In interpreter ... ?- thrower(4). 4 Yes ?- thrower(0). ERROR: Unhandled exception: zeroException ?- catch(thrower(0), zeroException, handler). zeroException Yes • Without exceptions catch is like call/1 • Thrown exception must unify with catcher form

  24. End

More Related