Python except keyword

Example

If a statement raises an error, print "Something went wrong":

try:
  x > 3
except:
  print("Something went wrong")

Run Instance

Definition and Usage

The keyword 'except' is used in the try ... except block. It defines the code block to be executed when an error is raised in the try block.

You can define different blocks for different error types, as well as blocks to be executed when there are no problems, please refer to the following examples.

More Examples

Example 1

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

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 does 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