Fehlerbehandlung

import operator
def harmonic(*arg):
  return len(arg)/reduce(operator.add, map(lambda x:1.0/x, arg))
>>> harmonic(1,5,0,3)
Traceback (most recent call last):
 File "<stdin>", line 1, in ?
 File "<stdin>", line 2, in harmonic
 File "<stdin>", line 2, in <lambda>
ZeroDivisionError: float division

Abfangen von Exceptions

>>> try: harmonic(1,5,0,3)
... except ZeroDivisionError, message: print "Division durch Null:", message
...
Division durch Null: float division

Aufräumarbeiten

f=open("/tmp/daten.txt")
try: do_something_with_file(f)
finally: f.close()