Search⌘ K
AI Features

The try and except Blocks

Explore how to handle exceptions in Python using try and except blocks. Learn to catch specific errors, manage nested exceptions, and use multiple except clauses to maintain control flow in your programs.

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

Python 3.8
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 ...