Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Formatting containers using format() in Python
Next article icon

Error Handling in Python using Decorators

Last Updated : 21 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 
 


Next Article
Formatting containers using format() in Python
author
rakshita_iyer
Improve
Article Tags :
  • Python
  • Python Decorators
Practice Tags :
  • python

Similar Reads

  • Memoization using decorators in Python
    Recursion is a programming technique where a function calls itself repeatedly till a termination condition is met. Some of the examples where recursion is used are a calculation of fibonacci series, factorial, etc. But the issue with them is that in the recursion tree, there can be chances that the
    3 min read
  • Formatting containers using format() in Python
    Let us see how to format containers that were accessed through __getitem__ or getattr() using the format() method in Python. Accessing containers that support __getitem__a) For Dictionaries C/C++ Code # creating a dictionary founder = {'Apple': 'Steve Jobs', 'Microsoft': 'Bill Gates'} # formatting p
    1 min read
  • How to use Function Decorators in Python ?
    In Python, a function can be passed as a parameter to another function (a function can also return another function). we can define a function inside another function. In this article, you will learn How to use Function Decorators in Python. Passing Function as ParametersIn Python, you can pass a fu
    3 min read
  • Decorators in Python
    In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
    10 min read
  • Nested Decorators in Python
    Everything in Python is an object. Even function is a type of object in Python. Decorators are a special type of function which return a wrapper function. They are considered very powerful in Python and are used to modify the behaviour of a function temporarily without changing its actual value. Nes
    2 min read
  • Dispatch Decorator in Python
    Decorators are a very powerful and useful tool in Python since it allows programmers to modify the behavior of function or class. Decorators allow us to wrap another function in order to extend the behavior of the wrapped function, without permanently modifying it. Example: # defining a decorator de
    2 min read
  • Correcting EOF error in python in Codechef
    EOF stands for End Of File. Well, technically it is not an error, rather an exception. This exception is raised when one of the built-in functions, most commonly input() returns End-Of-File (EOF) without reading any data. EOF error is raised in Python in some specific scenarios: Sometimes all progra
    3 min read
  • Timing Functions With Decorators - Python
    Everything in Python is an object. Functions in Python also object. Hence, like any other object they can be referenced by variables, stored in data structures like dictionary or list, passed as an argument to another function, and returned as a value from another function. In this article, we are g
    4 min read
  • Handling TypeError Exception in Python
    TypeError is one among the several standard Python exceptions. TypeError is raised whenever an operation is performed on an incorrect/unsupported object type. For example, using the + (addition) operator on a string and an integer value will raise a TypeError. ExamplesThe general causes for TypeErro
    3 min read
  • Data Hiding in Python
    In this article, we will discuss data hiding in Python, starting from data hiding in general to data hiding in Python, along with the advantages and disadvantages of using data hiding in python. What is Data Hiding? Data hiding is a concept which underlines the hiding of data or information from the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences