Home >>Python Keywords >Python except Keyword

Python except Keyword

Python except Keyword

The except keyword in python is used to define a block of code to run if in case a try block raises an error. By using this keyword, you can execute blocks and different blocks for different error types if nothing went wrong.

Here is an example of Python except Keyword:

try:
  x > 5
except:
  print("All is not well")
print("Even if it raised an error, the program keeps running")

Output:
All is not well
Even if it raised an error, the program keeps running
Example 2:

y = "hello"
try:
  y > 5
except NameError:
  print("variable that is not defined.")
except TypeError:
  print(" comparing values of different type")

Output:
Comparing values of different type