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.
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: |
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 |
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: |
The code throws a NameError that the except block then catches. Giving you a nice useful output:
➜ ~ python3 example.py |
You can raise your own type of exceptions
z = -1 |
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: |
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:
We can also be specific about the type of exception we want to catch:
except ValueError: |
If you are a Python beginner, then I highly recommend this book.