Python except keyword

Voorbeeld

Als een statement een fout oproept, wordt "Iets ging mis" afgedrukt:

try:
  x > 3
except:
  print("Iets ging mis")

Run Instance

Definitie en gebruik

Het keyword 'except' wordt gebruikt in het 'try ... except' blok. Het definieert de codeblokken die moeten worden uitgevoerd wanneer een fout wordt opgetreden in het 'try' blok.

U kunt verschillende blokken definiëren voor verschillende fouttypen, evenals blokken die worden uitgevoerd zonder probleem. Zie het volgende voorbeeld.

More Examples

Example 1

If a NameError is raised, write a message, and if a TypeError is raised, write another message:

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 types")

Run Instance

Example 2

Attempt to execute a statement that raises an error but do not define an error type (in this case 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 types")
except:
  print("Something else went wrong")

Run Instance

Example 3

If no error occurs, write a message:

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 types")
else:
  print("The 'Try' code was executed without raising any errors!")

Run Instance

Related Pages

try Keyword

finally Keyword