Python tranne Keyword
Esempio
Se l'istruzione genera un errore, stampa "Qualcosa è andato storto":
try:
x > 3
except:
print("Something went wrong")
Definizione e utilizzo
La except
parola chiave è usata in try... eccetto i blocchi. Definisce un blocco di codice da eseguire se il blocco try genera un errore.
È possibile definire blocchi diversi per diversi tipi di errore e blocchi da eseguire se nulla è andato storto, vedere gli esempi di seguito.
Altri esempi
Esempio
Scrivi un messaggio se è un NameError e un altro se è un TypeError:
x = "hello"
try:
x > 3
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
Esempio
Prova a eseguire un'istruzione che genera un errore, ma nessuno dei tipi di errore definiti (in questo caso, ZeroDivisionError):
try:
x = 1/0
except NameError:
print("You have a
variable that is not defined.")
except TypeError:
print("You
are comparing values of different type")
except:
print("Something else went wrong")
Esempio
Scrivi un messaggio se non sono stati generati errori:
x = 1
try:
x > 10
except NameError:
print("You have a variable that is not defined.")
except TypeError:
print("You are comparing values of different type")
else:
print("The 'Try' code was executed without raising any errors!")
Pagine correlate
La try
parola chiave.
La finally
parola chiave.