EXCEPTIONS, ASSERTIONS 6.00.01X LECTURE 1
EXCEPTIONS AND ASSERTIONS what happens when procedure execution hits an unexpected condition ? get an exception… to what was expected•trying to access beyond list limits test = [1,7,4]testIndexError•trying to convert an inappropriate type int(test)TypeError•referencing a non-existing variable aNameError•mixing data types without coercion 'a'/4 TypeError 6.00.01X LECTURE 2
OTHER TYPES OF EXCEPTIONS already seen common error types: • SyntaxError : Python can’t parse program • NameError : local or global name not found • AttributeError : attribute reference fails • TypeError : operand doesn’t have correct type • ValueError : operand type okay, but value is illegal • IOError : IO system reports malfunction (e.g. file not found) 6.00.01X LECTURE 3 "
WHAT TO DO WITH EXCEPTIONS? what to do when encounter an error? fail silently : • substitute default values or just continue • bad idea! user gets no warning return an “error” value • what value to choose? • complicates code having to check for a special value stop execution, signal error condition • in Python: raise an exception raise Exception("descriptive string") 6.00.01X LECTURE 4
DEALING WITH EXCEPTIONS Python code can provide handlers for exceptions try : a = int ( input ( "Tell me one number:" )) b = int ( input ( "Tell me another number: ")) print (a/b) print ( "Okay" ) except : print ( "Bug in user input." ) print ( ”Outside" ) exceptions raised by any statement in body of try are handled by the except statement and execution continues after the body of the except statement 6.00.01X LECTURE 5
HANDLING SPECIFIC EXCEPTIONS have separate except clauses to deal with a particular type of exception try : a = int ( input ( "Tell me one number: " )) b = int ( input ( "Tell me another number: " )) print ( "a/b = " , a/b) print ( "a+b = " , a+b) except ValueError : print ( "Could not convert to a number .” ) except ZeroDivisionError : print ( "Can't divide by zero” ) except : print ( "Something went very wrong .” ) 6.00.01X LECTURE 6
You've reached the end of your free preview.
Want to read all 27 pages?
- Fall '05
- Subroutine, Control flow, Division by zero