# exceptions.py print ''' Unlike other demo code, this script is not executable; it uses pseudo-code. ''' raise SystemExit # Simple, standard case try: x = 1/0 except ZeroDivisionError: x = None # Alternatively: # x = 0 # Don't use bare except try: db.connect() db.execute(sql) except: ''' What do we do here? We don't know what kind of exception we have, plus we might be catching things we don't want, like KeyboardInterrupt ''' db.close() # Use this instead: try: db.connect() db.execute(sql) except DBError: db.rollback() db.close() # try/finally example # Make sure that lock gets cleaned up # Note that exception gets propagated past finally # until caught by except (or program terminates) try: lock.acquire() processData() finally: lock.release() # To handle exception *and* clean up, use try/finally # wrapped around try/except: try: try: lock.acquire() db.connect() db.execute(sql) except DBError: db.rollback() finally: db.close() lock.release() # Multiple exceptions try: a,b = getInput() return int(a/b) except (ValueError, ArithmeticError): return None try: db.connect() db.execute(sql) except DBError: db.rollback() except KeyboardError: db.close() raise db.close() # Exception info try: page = urllib.urlopen(url).read() except IOError, error: print "Download failed due to %s", error # User-defined exception class MyException(Exception): pass def f(): for result in getInput(): if result is None: raise MyException, "No valid input" process(result) try: f() except MyException, error: print error cleanup()