Python Exception Handling – Python Tutorial

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?

An 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'.
python exception handling

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 ... except blocks.
  • try block is followed by one or more except clauses.
  • The code to be handled is written inside try clause and the code to be executed when an exception occurs is written inside except clause.
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
python exception handling
  • You can observe from the output that execution of statements, present, after exception are skipped.

Raising Exceptions

The raise keyword 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 TypeError when both a or b 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.
Example 1:
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.
python exception handling
  • CustomError is raised in above example, instead of TypeError.

Using ‘finally’ clause

The 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.

Example 1
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 with try ... except clauses.
  • Statements under else clause are executed only when no exception occurs in try clause.
Example 2
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!!!

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?
try:
#code
except:
# code
else:
# code

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?
x=10
y=20
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 🙂

8 thoughts on “Python Exception Handling – Python Tutorial

  1. I like what you guys are up also. Such smart work and reporting! Keep up the superb works guys I have incorporated you guys to my blogroll. I think it’ll improve the value of my site 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *