Skip to content
Related Articles

Related Articles

Error Handling in Python using Decorators

Improve Article
Save Article
Like Article
  • Difficulty Level : Easy
  • Last Updated : 21 Sep, 2021

Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. 

Example:

Python3




# defining decorator function
def decorator_example(func):
    print("Decorator called")
    # defining inner decorator function
    def inner_function():
            print("inner function")
            func()
    return inner_function
   
# defining outer decorator function
@decorator_example
def out_function():
    print("outer function")
out_function()

Output:

Decorator called
inner function
outer function

Error handling using decorators

The following example shows how a general error handling code without use of any decorator looks like:

Python3




def mean(a,b):
    try:
        print((a+b)/2)
    except TypeError:
        print("wrong data types. enter numeric")
 
 
def square(sq):
    try:
        print(sq*sq)
    except TypeError:
        print("wrong data types. enter numeric")
 
 
def divide(l,b):
    try:
        print(b/l)
    except TypeError:
                print("wrong data types. enter numeric")
mean(4,5)
square(21)
divide(8,4)
divide("two","one")

Output :

4.5
441
0.5
wrong data types. enter numeric

Even though there is nothing logically wrong with the above code but it lacks clarity. To make the code more clean and efficient decorators are used for error handling. The following example depicts how the above code can be more presentable and understandable by use of decorators:

Python3




def Error_Handler(func):
    def Inner_Function(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except TypeError:
            print(f"{func.__name__} wrong data types. enter numeric")
    return Inner_Function
@Error_Handler
def Mean(a,b):
        print((a+b)/2)
     
@Error_Handler
def Square(sq):
        print(sq*sq)
 
@Error_Handler
def Divide(l,b):
        print(b/l)
     
Mean(4,5)
Square(14)
Divide(8,4)
Square("three")
Divide("two","one")
Mean("six","five")

Output :

4.5 

196 

0.5 

Square wrong data types. enter numeric 

Divide wrong data types. enter numeric 

Mean wrong data types. enter numeric 
 


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!