






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An overview of error handling in python, focusing on exceptions and recovery techniques such as try-except blocks and creating custom exceptions. It covers various types of errors, recovering from specific error types, and the hierarchy of exceptions. The document also includes examples and exercises to help readers understand the concepts.
Typology: Slides
1 / 11
This page cannot be seen from the preview
Don't miss anything!







Q1: What happens when an error causes a crash? TypeError: unsupported operand type(s) for +: 'int' and 'list' IndexError: list index out of range Understanding this helps you debug. Q2: Can we use "problem-signalling" to handle unusual situations more smoothly? Understanding this helps you write more flexible code. It is sometimes better to warn and re-prompt the user than to have the program crash (even if the user didn't follow your exquisitely clear directions or preconditions).
ZeroDivisionError: integer division or modulo by zero name of the type of the exception object string kept in the exception object When various bad things happen, Python creates an exception object. If that object is not otherwise "handled", the system halts, printing the stack trace and info about the exception object.
Try-except blocks allow us to recover from errors Do the code that is in the try-block If an error occurs, jump to the except-block (skip it o.w.) def recip(x): """Return 1.0/x, or inf if x is 0. Pre: x is a number""" try: return 1.0/x except: return float('Inf') executes if an error occurs
def recip(x): """Return 1.0/x, or inf if x is 0""" try: return 1.0/x except ZeroDivisionError: return float('Inf')
def recip4(): """Return reciprocal of user input (we don't handle 0)""" prompt = "Pick a non-zero number: " while True: try: n = float(raw_input(prompt)) return 1.0/n except ZeroDivisionError: print 'The number has to be non-zero; please try again.' except ValueError: print 'The input has to be a number; please try again.' The only escape is if valid input is given in the try block, so the that return statement succeeds.
def speed(x): if x > 3e8: raise ValueError('speed: input > light speed') You can signal errors by creating exceptions with raise. You can choose an informative output message The type is informative to the user (or enclosing except-blocks) As usual, creates a new object.
class SpeedError(StandardError): """An instance signals violation of a speed constraint.""" pass Exceptions provide a mechanism for your functions to communicate with each other: Callees can "hand" downstream callers an exception to signal that something unusual happened.
Rules of thumb: For simple tests and "normal" situations, if-thens are usually better. For precondition violations, asserts are more readable. (Note: asserts raise AssertionErrors.) For more "abnormal" situations, try-excepts are better. There are some canonical try-except idioms, such as processing malformed user input (which we just saw).