The else block when catching exceptions in Python
You can also add a else block to the try-except construct. An important nuance is that the code placed in the else block will work if no exceptions were caught before it in try-except.
Let's say we have a list:
lst = [1, 2, 3]
In the try-except construction, we will write an exception catch for a non-existent list element:
try:
print(lst[4])
except IndexError:
print('error: elem is not exist')
Now let's specify in the else block the output of the sum of all elements of the list:
try:
print(lst[4])
except IndexError:
print('error: elem is not exist')
else:
print(sum(lst))
If the code in the try block refers to a missing element, an error message will appear in the console:
'error: elem is not exist'
Now let's set the try block to output an element that is definitely in the list:
try:
print(lst[0])
except IndexError:
print('error: elem is not exist')
else:
print(sum(lst))
After executing the code, two numbers will appear in the console: the element specified in try and the sum of all elements of the list:
1
6
Given a list:
lst = [1, 2, 3]
Write code to catch the division by zero exception. If the exception does not occur, print the length of the list.