User Defined Exceptions in python

Rumman Ansari   Software Engineer   2022-10-03   184 Share
☰ Table of Contents

Table of Content:


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)
User Defined Exceptions

Example 1 continued ...

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 of TypeError.
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.

Example 1

def divide(a,b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        print("Dividing by Zero.")
    finally:
        print("In finally clause.")
Using 'finally' clause

Example 1 continued ...

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!!!