Sometimes code throws an exception.

You can catch that exception using the try-except block.

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:

Try-except example

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

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:')

x = int(rawInput)
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')

Download exercises