Overview of Unhandled Exceptions¶
Let us see how we can handle general or unhandled exceptions.
- As part of the code developed, we might not be able to handle all the exceptions.
- When it comes to class hierarchy in Python, Exception is the root class. All unhandled exceptions can be dealt with
Exception
as part ofcatch
.
In [1]:
# This code handles only type error
# As b = 'ten', it will throw ValueError
a = 1
b = 'ten'
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}')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Input In [1], in <cell line: 5>() 4 b = 'ten' 5 try: ----> 6 res = int(a) + int(b) 7 except TypeError: 8 print(f'Either {a} or {b} or both are not of integer type') ValueError: invalid literal for int() with base 10: 'ten'
In [2]:
# By adding Exception, if the code raises any unhandled exceptions
# then they will be redirected to generic Exception
a = 1
b = 'ten'
try:
res = int(a) + int(b)
except TypeError:
print(f'Either {a} or {b} or both are not of integer type')
except Exception:
print(f'Unhandled exeception while adding {a} and {b}')
else:
print(f'Sum of {a} and {b} is {res}')
Unhandled exeception while adding 1 and ten
In [3]:
# finally will work in the same way as before.
# The code in the finally block will always execute
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')
except Exception:
print(f'Unhandled exeception while adding {a} and {b}')
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