250 likes | 278 Views
Learn about managing exceptions, handling errors, and designing effective exception handling mechanisms in programming. Understand how different languages like C, Java, and C++ approach exceptions, with insights into best practices for modular and robust code.
E N D
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
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
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
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
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
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
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?
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)
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
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!
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 …
Java Exception Classes Object Throwable Error Exception RuntimeException User Defined Errors and Runtime Exceptions: Thrown by system, Unchecked Other Exceptions: Checked
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 }
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
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
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”
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
More Extensive Example • PostfixCalc …
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
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()
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
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