Python | Exceptions | try/except statement

The try/except statement can be used to handle exceptions when they occur.

The try block contains code that might throw an exception. If that exception occurs, the code in the try block stops being executed, and the code in the except block is run. If no error occurs, the code in the except block doesn’t run.

Example:

try:
	num1 = 5
	num2 = 0
	print (num1/num2)
	print("I am done!")
except ZeroDivisionError:
	print("An error occurred")
	print("due to zero division")

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
An error occurred
due to zero division
ddn_ro@linux:~/Desktop$

Normally, the try block gives an error, a ZeroDivisionError . The except ZeroDivisionError: says that when that error occurs print the two statements shown in the code. So it did!

A try statement can have multiple different except blocks to handle different exceptions.
They can be put into a single except block using parentheses.

try:
	variable = 6
	print(variable + "hello")
	print(variable / 2)
except ZeroDivisionError:
	print("Divided by zero")
except (ValueError, TypeError):
	print("Error occurred")

The terminal output will be:

ddn_ro@linux:~/Desktop$ python file.py
Error occurred
ddn_ro@linux:~/Desktop$

The error occurred because an integer can not be added to a string. So, the except (ValueError, TypeError) occurs.

Leave a Reply