Exception handling in Python

Rumman Ansari   Software Engineer   2023-03-31   386 Share
☰ Table of Contents

Table of Content:


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.

  • 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

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.

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 either a or b are not integers.