Python versione Bignami - Le eccezioni

Sintassi

try:
    # Codice
    raise BadError
    # Altro codice
    raise VerboseError("long description")
except BadError:
    # Executed if BadError happens
except (OneError, AnotherError):
    # Executed if OneError or AnotherError happen
except VerboseError, ve:
    # Catch VerboseError and its exception object
    print ve.description
except:
    # Catches all exceptions not catched before
    print "unknown bad things happened"
    # Reraises the exception
    raise
else:
    # Executed if no exception is raised
finally:
    # Executed always, even if exceptions are not caught or thrown or rethrown
    # in the except handlers.

Esempi:

# Crea un file e lo copia su un'altra macchina con scp
try:
    file = open(filename, "w")
    print >>file, value
    file.close()
    subprocess.check_call(["/usr/bin/scp", filename, "host:"])
except IOError:
    # Handle errors opening or writing to the file
    # ...
except CalledProcessError e:
    # Handle the case of scp returning a non-0 status
    # ...
    print >>sys.stderr, "Scp returned nonzero status", e.errno
else:
    print "The results are now on host in the file", filename
finally:
    try:
        os.remove(filename)
    except:
        # Ignore all errors trying to remove the file
        pass

Link