Python

Try except

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: Complete Python Bootcamp: Go from zero to hero in Python

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

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

except ValueError:
print('Invalid input specified')
Previous Post Next Post

Cookie policy | Privacy policy | ©