1 min read

Python Error and Exception Handling

Errors and exceptions can be handled in Python using try...except blocks.

try...except

The try block lets you test a block of code for errors. The except block lets you handle the error.

try:
  print(x)
except:
  print("An exception occurred")

finally

The finally block, if specified, will be executed regardless if the try block raises an error or not.

try:
  print(x)
except:
  print("Something went wrong")
finally:
  print("The 'try except' is finished")

Raising an Exception

You can raise an exception using the raise keyword.

x = -1

if x < 0:
  raise Exception("Sorry, no numbers below zero")