You can catch that exception using the try-except block. The try block lets you test a block of code for errors, the except block handles the errors and the finally block lets you execute code regardless of errors.

The try-except statement starts with a block of code, and a response is specified in case an exception is thrown.

Note: In other programming languages this is often called try-catch.

Related Course: Complete Python Programming Course & Exercises

Try-except example

The try-except example below throws an error, because variable z is not defined. But it doesn’t exit the program, it runs the code in the except block and then continues normal flow of the program.

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

print('Continue flow')

Without a try-except block, Python would quit the program on every error that occurs. The above example shows the program continues, despite the error having occured. The except block lets you handle the error. Not all errors are fatal.

➜  ~ python3 example.py 
An exception occurred
Continue flow
➜ ~

There are different types of exceptions. The try-except block lets you handle different type of Exceptions and do something different for each type of exception that occurs.

try:
print(z)
except NameError:
print("Variable z is not defined")
except:
print("Another type of exception has occured")

The code throws a NameError that the except block then catches. Giving you a nice useful output:

➜  ~ python3 example.py 
Variable z is not defined
➜ ~

You can raise your own type of exceptions

z = -1

if z < 0:
raise Exception("Invalid number, z is below zero")

Finally

The finally block is executed after the try-except block has been completed. This is executed regardless of wheter the code block is successfully or threw errors.

try:
print(z)
except:
print("Exception occured")
finally:
print("The 'try except' is finished")

After execution of the try-except-finally block, the program continues the normal execution flow.

Related Course: Complete Python Programming Course & Exercises

Keyboard input

You can use the try-except block to do keyboard input validation.

Lets say we want to get numeric input from the keyboard and calculate the number squared.
The straight forward method would be:

# get keyboard input (string)
rawInput = input('Enter number:')

# convert string to integer
x = int(rawInput)

# calculate number squared
print(x*x)

This works as long as we give numeric input. If we would type “two”, the program crashes - an exception is thrown. That’s where try-catch comes in:

rawInput = input('Enter number:')

try:
x = int(rawInput)
print(x*x)
except:
print('Invalid input specified')

Try some inputs:

try except

We can also be specific about the type of exception we want to catch:

except ValueError:
print('Invalid input specified')

If you are a Python beginner, then I highly recommend this book.

Download exercises