7

Error Handling in Python using Decorators

 2 years ago
source link: https://www.geeksforgeeks.org/error-handling-in-python-using-decorators/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Error Handling in Python using Decorators
Error Handling in Python using Decorators

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("outter function")
out_function()

Output:

Decorator called
inner function
outter 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 :

Square wrong data types. enter numeric

Divide wrong data types. enter numeric

Mean wrong data types. enter numeric

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK