280 likes | 398 Views
CS 112 Intro to Programming Exceptions. George Mason University. Exception Handling: Basic Syntax. try : #watch for exceptions here try_suite except : #exception handling code except_suite. A piece of code that is potential to crash in runtime. 2. Exceptions Hierarchy. BaseException
E N D
CS 112 Intro to Programming Exceptions George Mason University
Exception Handling: Basic Syntax try:#watch for exceptions heretry_suiteexcept:#exception handling codeexcept_suite A piece of code that is potential to crash in runtime 2
Exceptions Hierarchy BaseException +-- KeyboardInterrupt +-- Exception +-- ArithmeticError | +-- ZeroDivisionError +-- EnvironmentError | +-- IOError +-- EOFError +-- LookupError | +-- IndexError | +-- KeyError +-- NameError +-- SyntaxError +-- SystemError +-- TypeError +-- ValueError • There are many exception classes organized into a hierarchy→ using inheritance (parent and child class relationships) • (found at http://docs.python.org/3.2/library/exceptions.html) Whenever a runtime error occur in ‘try’, the ‘except’ will handle this specific exception (event)
Validating Input Loop continues to execute, raising and handling exceptions, until user complies.
Validating Input Loop continues to execute, raising and handling exceptions, until user complies. demo$ python3 e4.py #: 5 successfullygot x: 5 #: asdf name 'asdf' is not defined #: 3/0 division by zero Exception1 Exception2
Exception Handling There are three basic choices when handling exceptions: • handle it • defer it up the calling chain • do both: handle it, but also defer it to the caller. Example: • if method A calls method B, and then B calls method C, and C raises an exception: • C can handle it • C can defer it to B (the caller of C)→ B, and in turn, A, then have the same choices • C can handle it and then re-raise it 6
Exception Handling Propagate (report the error) I will handle it 7
Validating Input Loop continues to execute, raising and handling exceptions, until user complies. demo$ python3 e4.py #: 5 successfullygot x: 5 #: asdf name 'asdf' is not defined #: 3/0 division by zero Exception1 Exception2
Exception Handling defer Ouch! I will handle it 9
Deferring Exceptions • exception raised in buggycrashes (propagates) out to whatever called it: main, in this case. • main catches the exception. demo$ python3 e12.py #? 10 0.5 demo$ python3 e12.py #? 0 sadly, wecannot do zero division. demo$ python3 e12.py #? asdf Traceback … ValueError… 10
Exception Handling Propagate (report the error) defer Ouch! I will handle it 11
Exception Handling Defer the rest Defer the rest I will handle some I will handle some 12
Deferring Some Exceptions • ValueErrors caught in buggy. • ZeroDivisionErrors propagated to main, caught there. • TypeErrors propagated all the way, crashing entire program. demo$ python3 e13.py #? 3 1.6666666666666667 demo$ python3 e13.py #? "hello" didn'tget an int! 0 demo$ python3 e13.py #? 0 sadly, wecannot do zero division. demo$ #? (1,2,3) Traceback … TypeError… 13
Deferring - another example • KeyError handled in find() • ZeroDivisionErrordeferred in find(), then handled in main() • ValueErrors unhandled. demo$ python3 e14.py #? 6 a demo$ python3 e14.py #? 4 redherring demo$ python3 e14.py #? 0 sadly, wecannot do zero division. demo$ python3 e14.py #? asdf Traceback…ValueError… 14
Exception Handling Login bank account Count failed times Verify the password Defer the rest Defer the rest I will handle some I will handle some If the exception is handled by C, then B will not notice it 15
Exception Handling Login bank account Count failed times Verify the password Re-raise I will handle it I will handle it, too After the exception is handled by C, we will manually inform B 16
Raising Exceptions • We can generate an exception on purpose(and hopefully catch it somewhere else!) • done with a raise statement, which needs an expression of some Exception type. This usually means calling a constructor (__init__). Examples: • raiseException("boo!")raiseArithmeticError ("this doesn't add up!")raiseValueError("needed a positive number") • except IOError as e: print ("catching it, re-raising it.")raise e
Exceptions Hierarchy BaseException +-- KeyboardInterrupt +-- Exception +-- ArithmeticError | +-- ZeroDivisionError +-- EnvironmentError | +-- IOError +-- EOFError +-- LookupError | +-- IndexError | +-- KeyError +-- NameError +-- SyntaxError +-- SystemError +-- TypeError +-- ValueError • There are many exception classes organized into a hierarchy→ using inheritance (parent and child class relationships) • (found at http://docs.python.org/3.2/library/exceptions.html) Build-in exception, everyone know what they means
Raising Exceptions Reusing/raising a few specific exception types is useful: • Exception for general issues (but a bit vague) • TypeError, when the supplied arg. was the wrong type • ValueError when your code only should be run on some batch of values and the wrong one was given • Any of them can be reused if it suits your purpose, just call their constructor (see examples on previous slide) Then you can raise them and catch them as before. → but you can also make brand new types of exceptions!
Re-raising the Same Exception • We can directly re-raise the caught exception object. • To force this exception propagate, since by default exception only get handled once • No need to construct an exception value-we already have an exception object. note the quotes! demo$ python3 e16.py #: 'a' in get_input: could not convert string to float: 'a' in main:could not convert string to float: 'a' 20
Re-raising Another Exceptions • Initialize an exception ourselves • We want to customized the error information to the caller note the quotes! demo$ python3 e15.py #: 'asdf' in get_input: could not convert string to float: 'asdf' in main: ERR demo$ python3 e15.py #: (1,2,3) in main:float() argument must be a string or a number demo$ python3 e15.py #: asdf Traceback…NameError… 21
Exception Handling Login bank account Count failed times Verify the password Re-raise I will handle it I will handle it, too After the exception is handled by C, we will manually inform B 22
Exceptions and Classes Did you find initialization of an exception looks the same as initialization of an object of a class? Actually exceptions are just a kind of class:
Exceptions Hierarchy BaseException +-- KeyboardInterrupt +-- Exception +-- ArithmeticError | +-- ZeroDivisionError +-- EnvironmentError | +-- IOError +-- EOFError +-- LookupError | +-- IndexError | +-- KeyError +-- NameError +-- SyntaxError +-- SystemError +-- TypeError +-- ValueError • There are many exception classes organized into a hierarchy→ using inheritance (parent and child class relationships) • (found at http://docs.python.org/3.2/library/exceptions.html) Inheritance relations We usually define customized exception as child class of build-in ones
User-Defined Exceptions We can create our own types of exceptions. They can be raised, propagated, and caught just like any other exception types. 25
User-Defined Exceptions • raise keyword used with a call to our exception's constructor • except-block used with our new type of exception demo$ python3 e11.py #? 5 50 demo$ python3 e11.py #? 13 uhoh: that'sunlucky! demo$ python3 e11.py #? asdf invalidliteral for int() with base 10: 'asdf' Raise an exception just like: If want to trigger this event, then raise this exception 26
Example: using exception handling in classes • A class can use exceptions within its methods, just like we've done before. demo$ python3 -i e17.py >>> alice = Artist() >>> alice.set_name("Alice Cooper") too long!
Example: using instance variables in exceptions demo$ python3 -i e18.py >>> alice = Artist() >>> alice.set_name("Alice Cooper") too long! (12) Our exceptions are objects, and they can have/use instance variables like data.