Exception Handling – else and finally¶
Let us go through else and finally.
- Some times we might want to log all sucessful executions. We can leverage
else
for it. - If no exceptions are raised or thrown, then the code in
else
block will be executed. - The code in the
finally
will be executed all the time. Typically we usefinally
to ensure that any open database connections closed irrespective whether exceptions are raised or not. - We also use
finally
to generate informational logs.
In [1]:
a = 1
In [2]:
b = 'ten'
In [3]:
int(a) + int(b)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [3], in <cell line: 1>() ----> 1 int(a) + int(b) ValueError: invalid literal for int() with base 10: 'ten'
In [4]:
try:
res = int(a) + int(b)
except TypeError:
print(f'Either {a} or {b} or both are not of integer type')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [4], in <cell line: 1>() 1 try: ----> 2 res = int(a) + int(b) 3 except TypeError: 4 print(f'Either {a} or {b} or both are not of integer type') ValueError: invalid literal for int() with base 10: 'ten'
In [5]:
a = 1
b = '10'
try:
res = int(a) + int(b)
except TypeError:
print(f'Either {a} or {b} or both are not of integer type')
else:
print(f'Sum of {a} and {b} is {res}')
Sum of 1 and 10 is 11
In [6]:
a = 1
b = '10'
try:
res = int(a) + int(b)
except TypeError:
print(f'Either {a} or {b} or both are not of integer type')
else:
print(f'Sum of {a} and {b} is {res}')
finally:
print(f'Performed arithmetic operation on {a} and {b}')
Sum of 1 and 10 is 11 Performed arithmetic operation on 1 and 10
In [7]:
a = 1
b = 'ten'
try:
res = int(a) + int(b)
except ValueError:
print(f'Either {a} or {b} or both are not of integer type')
else:
print(f'Sum of {a} and {b} is {res}')
finally:
print(f'Performed arithmetic operation on {a} and {b}')
Either 1 or ten or both are not of integer type Performed arithmetic operation on 1 and ten