Exceptions
- An
exception
is an error that occurs during execution of a program. - Python allows a programmer to handle such exceptions using
try ... except
clauses, 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 ... except
blocks. - A
try
block is followed by one or moreexcept
clauses.
- The code to be handled is written inside
try
clause and the code to be executed when an exception occurs is written insideexcept
clause.
Sample Exception Handling
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
raise
keyword is used when a programmer wants a specific exception to occur.
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
TypeError
when botha
orb
are not integers.
User Defined Functions
- There are many built-in exceptions in Python, which are directly or indirectly derived from
Exception
class. - Python also allows a programmer to create custom exceptions, derived from base
Exception
class.
class CustomError(Exception): def __init__(self, value): self.value = value def __str__(self): return str(self.value) try: a = 2; b = 'hello' if not (isinstance(a, int) and isinstance(b, int)): raise CustomError('Two inputs must be integers.') c = a**b except CustomError as e: print(e)
Output
Two inputs must be integers.
CustomError
is raised in above example, instead ofTypeError
.
Using ‘finally’ clause
finally
clause is an optional one that can be used withtry ... except
clauses.
- All the statements under
finally
clause are executed irrespective of exception occurrence.
def divide(a,b): try: result = a / b return result except ZeroDivisionError: print("Dividing by Zero.") finally: print("In finally clause.") print('First call') print(divide(14, 7)) print('Second call') print(divide(14, 0))
Output
First call
In finally clause.
2.0
Second call
Dividing by Zero.
In finally clause.
None
- Statements inside
finally
clause are executed in both function calls.
Using ‘else’ clause
else
clause is also an optional clause withtry ... except
clauses.- Statements under
else
clause are executed only when no exception occurs intry
clause.
try: a = 14 / 7 except ZeroDivisionError: print('oops!!!') else: print('First ELSE') try: a = 14 / 0 except ZeroDivisionError: print('oops!!!') else: print('Second ELSE')
Output
First ELSE
oops!!!