How to use Python Try Except Block

try except blocks in Python allow you to handle errors that may arise in your program. One example of this might be if you are using an API and if the program does not receive the data it expects, it would likely cause the program to throw a ValueError and crash. By putting the code inside a try except block you can catch this error and handle it in any way you want with the program continuing to run.

 

Try Except Sytnax

A try except block in Python has three main components, which work like this:

 

try:
  # attempt to execute some code...
except:
  # the code threw an error so handle the exception here...
finally:
  # an optional block for executing code regardless of an error...

 

The finally statement is optional; in most cases, you will only be using try and except, but you can also use an else statement and additional except statements if needed – we will learn about those further into this tutorial.

 

Exception Handling

The following is a basic example where we try to print a variable that isn't defined. Usually, this would cause a NameError and the program to crash but by putting the code inside a try except block we can handle the error and allow the program to continue running.

 

try:
  print(n)
except:
  print('An error occurred.')
   
print('hello')
An error occurred.
hello

 

Without doing the above the following would happen:

 

print(n)
   
print('hello')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-113-cbc963e15184> in <module>
----> 1 print(n)
     2
     3 print('hello')

NameError: name 'n' is not defined

 

Handle Different Exception Types

It is possible to handle exceptions differently depending on their type by using additional except statements with the exception to look for like this:

 

try:
  print(n)
except NameError:
  print("n is not defined...")
except:
  print("Some other problem happened...")
n is not defined...

 

Else Statement with Try Except Block

If no error happened and you would like to handle that, use the else statement like this:

 

try:
  print(n)
except:
  print("n is not defined...")
else:
  print('Code worked without an error...')
n is not defined...

 

Finally Statement

The finally statement is executed regardless of what happened within the rest of the try except block meaning it will always execute.

 

try:
  print(n)
except:
  print("n is not defined...")
finally:
  print('The block is finished.')
n is not defined...
The block is finished.