...

/

The try and except Blocks

The try and except Blocks

Learn about the usage of the try and except blocks in exception handling in Python.

How to use the try and except blocks

The try block

We enclose the code we suspect will cause an exception within the try block.

The except block

We catch the raised exception in the except block. It must immediately follow the try block.

Coding example

Press + to interact
a = 10
b = 0
try :
c = a/ b
print('c =', c)
except ZeroDivisionError :
print('Denominator is 0')

If no exception occurs while executing the try block, control goes to the first line beyond the except block.

If an exception occurs during the ...