Exception Handling in Python: A Complete Guide to Managing Errors
Table of Content:
Exceptions
-
An
exceptionis an error that occurs during execution of a program. -
Python allows a programmer to handle such exceptions using
try ... exceptclauses, thus avoiding the program to crash. -
Some of the python expressions, though written correctly in syntax, result in error during execution. Such scenarios have to be handled.
Sample Exceptions
-
Try executing the following two expressions
10 + ( 1 / 0)36 + '20' -
The first one throws error message,
ZeroDivisionError : division by zero, and -
Second one throws,
TypeError : unsupported operand type(s) for +: 'int' and 'str'.
In Python, every error message has two parts. The first part tells what type of exception it is and second part explains the details of error.
Handling Exception
-
Python handles exceptions using code written inside
try ... exceptblocks. -
A
tryblock is followed by one or moreexceptclauses. -
The code to be handled is written inside
tryclause and the code to be executed when an exception occurs is written insideexceptclause.
Sample Exception Handling
Example 1
try:
a = pow(2, 4)
print("Value of 'a' :", a)
b = pow(2, 'hello') # results in exception
print("Value of 'b' :", b)
except TypeError as e:
print('oops!!!')
print('Out of try ... except.')
Output
Value of 'a' : 16
oops!!!
Out of try ... except.
- You can observe from the output that execution of statements, present, after exception are skipped.
Raising Exceptions
raisekeyword is used when a programmer wants a specific exception to occur.
Example 2
try:
a = 2; b = 'hello'
if not (isinstance(a, int)
and isinstance(b, int)):
raise TypeError('Two inputs must be integers.')
c = a**b
except TypeError as e:
print(e)
Output
Two inputs must be integers.
- Above example raises
TypeErrorwhen eitheraorbare not integers.
- Question 1: What is the purpose of the try and except block in Python?
- Question 2: What are the different types of errors in Python?
- Question 3: How do you handle exceptions in Python?