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.
  • try: apre il blocco di codice su cui si gestiscono le eccezioni.
  • except Tipo: cattura le eccezioni di un tipo specifico.
  • except (Tipo1, Tipo2, Tipo3...): cattura le eccezioni di uno dei tipi dati.
  • except Tipo, valore: cattura le eccezioni di un tipo dato, gestendo non solo il tipo di eccezione ma anche l'oggetto eccezione lanciato.
  • except: gestisce tutte le eccezioni non gestite da altri except.
  • else: viene eseguito se non sono state lanciate eccezioni.
  • finally: viene eseguito sempre, anche se vi sono eccezioni non gestite.
  • raise Tipo lancia un'eccezione.
  • raise Tipo(arg1, arg2) lancia un'eccezione con l'oggetto e non solo il tipo. L'oggetto lanciato si può recuperare usando except Tipo, val:
  • raise rilancia l'eccezione che sta venendo gestita

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