Python Try Except

Python Try Except: Error Handling

When an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the try statement.


Basic Exception Handling

The try block will generate an exception because x is not defined. Without the try block, the program will crash and raise an error.

Try Except Example

try:
  print(x)
except:
  print("An exception occurred! 'x' is not defined.")

Catching Specific Errors

You can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error.

Multiple Exceptions

try:
  print(x)
except NameError:
  print("Variable x is not defined")
except:
  print("Something else went wrong")

The else and finally Blocks

You can use the else keyword to define a block of code to be executed if no errors were raised.

The finally block, if specified, will be executed regardless if the try block raises an error or not. This is highly useful for cleaning up resources, like closing files.

Else and Finally

try:
  print("Hello")
except:
  print("Something went wrong")
else:
  print("Nothing went wrong")
finally:
  print("The 'try except' is finished")

Raise an Exception

As a Python developer you can choose to throw an exception if a condition occurs using the raise keyword.

raise Exception("Sorry, no numbers below zero")