In this article, we are going to discuss Python Exception Handling. In the previous one, we had discussed the oops concept, inheritance, and polymorphism.
What is Python Exception?
exception is an error that occurs during the execution of a program. Errors are two types of syntax error ( it is occurred due to the wrong syntax of language) and exception error ( it has occurred when the program is syntactically correct but after the code resulted in an error. ).
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 errors during execution. Such scenarios have to be handled.
Sample Python Exceptions
- Try executing the following two expressions 10 + ( 1 / 0)36 + ’20’
- The first one throws an 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 the second part explains the details of the error.
Python Exception Handling
- Python handles exceptions using code written inside
try ... exceptblocks.
tryblock is followed by one or more
- The code to be handled is written inside
tryclause and the code to be executed when an exception occurs is written inside
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.')
- You can observe from the output that execution of statements, present, after exception are skipped.
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)
Two inputs must be integers.
- Above example raises
bare not integers.
User Defined Functions
- There are many built-in exceptions in Python, which are directly or indirectly derived from
- Python also allows a programmer to create custom exceptions, derived from base
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)
Two inputs must be integers.
CustomErroris raised in above example, instead of
Using ‘finally’ clause
finally clause is an optional one that can be used with
try ... 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))
First call In finally clause. 2.0 Second call Dividing by Zero. In finally clause. None
- Statements inside
finallyclause are executed in both function calls.
Using ‘else’ clause
elseclause is also an optional clause with
try ... exceptclauses.
- Statements under
elseclause are executed only when no exception occurs in
try: a = 14 / 7 except ZeroDivisionError: print('oops!!!') else: print('First ELSE') try: a = 14 / 0 except ZeroDivisionError: print('oops!!!') else: print('Second ELSE')
First ELSE oops!!!
FAQs on Python Exception Handling:
How many except statements can try-except block we have?
More than zero but we have to take at least one in the block.
Is the below following Python code valid or not?
Yes, it is valid.
What happens when ‘1’ == 1 is executed?
We get an error:
‘1’ == 1
^ SyntaxError: invalid character in identifier
What will be the output of the following Python code?
assert x>y, ‘X too small’
You will get a error: AssertionError: X too small
In this article we have successful executed the python exception handling with their type with suitable examples. In the coming one we will discuss about the Python modules.
Thank You 🙂