lec8_except - EXCEPTIONS ASSERTIONS 6.00.01X LECTURE 1 EXCEPTIONS AND ASSERTIONS what happens when procedure execution hits an unexpected condition get

lec8_except - EXCEPTIONS ASSERTIONS 6.00.01X LECTURE 1...

This preview shows page 1 - 7 out of 27 pages.

EXCEPTIONS, ASSERTIONS 6.00.01X LECTURE 1
Image of page 1
EXCEPTIONS AND ASSERTIONS what happens when procedure execution hits an unexpected condition ? get an exception… to what was expectedtrying to access beyond list limits test = [1,7,4]test[4]IndexErrortrying to convert an inappropriate type int(test)TypeErrorreferencing a non-existing variable aNameErrormixing data types without coercion 'a'/4 TypeError 6.00.01X LECTURE 2
Image of page 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 "
Image of page 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
Image of page 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
Image of page 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
Image of page 6
Image of page 7

You've reached the end of your free preview.

Want to read all 27 pages?

  • Fall '05
  • UmutAcar
  • Subroutine, Control flow, Division by zero

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture