• Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements
CODE OF GEEKS

We at CODE OF GEEKS, aim at providing best and quality content for our users at no extra cost.

    • Study Materials
      • InfyTQ Archive
      • Infosys Archive
      • TCS Archive
      • Accenture Archive
      • AMCAT Archive
      • Capgemini Archive
      • Cisco Archive
      • CoCubes Archive
      • Cognizant(CTS) Archive
      • Deloitte Archive
      • DXC Archive
      • Goldman Sachs Archive
      • Hexaware Technologies Archive
      • LTI Archive
      • MindTree Archive
      • Virtusa Archive
      • Wipro Archive
    • Interview Preparation
      • C Interview Questions
      • Data Structures Interview Questions
      • DBMS Interview Questions
      • HR Interview Questions
      • Java Interview Questions
      • Operating System Interview Questions
      • Python Interview Questions
      • SQL Query Interview Questions
    • Tutorials
      • Node.js Tutorial
      • Express.js Tutorial
      • Python Tutorial
    • Programming
      • C Programming MCQs
      • C Code Snippets – Output Questions
      • Python Code Snippets – Output Questions
      • Java Code Snippets – Output Questions
    • Aptitude
      • Verbal Ability for Placements
CODE OF GEEKS
CODE OF GEEKS
  • Study Materials
    • InfyTQ Archive
    • Infosys Archive
    • TCS Archive
    • Accenture Archive
    • AMCAT Archive
    • Capgemini Archive
    • Cisco Archive
    • CoCubes Archive
    • Cognizant(CTS) Archive
    • Deloitte Archive
    • DXC Archive
    • Goldman Sachs Archive
    • Hexaware Technologies Archive
    • LTI Archive
    • MindTree Archive
    • Virtusa Archive
    • Wipro Archive
  • Interview Preparation
    • C Interview Questions
    • Data Structures Interview Questions
    • DBMS Interview Questions
    • HR Interview Questions
    • Java Interview Questions
    • Operating System Interview Questions
    • Python Interview Questions
    • SQL Query Interview Questions
  • Tutorials
    • Node.js Tutorial
    • Express.js Tutorial
    • Python Tutorial
  • Programming
    • C Programming MCQs
    • C Code Snippets – Output Questions
    • Python Code Snippets – Output Questions
    • Java Code Snippets – Output Questions
  • Aptitude
    • Verbal Ability for Placements

User Defined Exceptions in Python with Examples

  • January 6, 2023
  • CODE OF GEEKS
  • 0
User Defined Exceptions in Python with examples
User Defined Exceptions in Python with examples

Just like different built-in exceptions, Python provides us the utility to create our own user defined exceptions or custom exceptions.

In all those scenarios where you need a specific exception to suite your purpose, we can use Custom Exception in Python.



Below are the steps to create a user-defined exception or custom exception in python,

1. Create a class derived from Exception class. This class will be your solution to create a custom exception.

Suggested Tutorial: Exception Handling in Python

class GiveException(Exception):
  def __init__(self, message):
    self.message = message

2. This Custom Exception is to be used when a developer feels there is need to do so. This Exception can be raised using raise keyword in Python.

raise GiveException('Hello')

3. This Exception can also handled using try-except block technique for Exception Handling.

try:
  // statements
except GiveException as msg:
  print(msg)

Let’s consider one example where we create our own exception for a banking system,

Problem: You are the admin of a MNC. Your task is to create a custom exception that should be raised when the paid leaves of an employee is less than 2.

Plan:

Create two .py files:
exception.py -> To define our exception
employee.py -> To implement our requirement

exception.py: This file defines our custom exception class. Currently, it just get’s initialized with a message.

class LeaveException(Exception):
    def __init__(self, message):
        print('XXXXXXXXXXXX LEAVE EXCEPTION RAISED XXXXXXXXXXXX')
        self.message = message
        # other statements

employee.py: This file contains the business logic.

# let's import our exception
from exception import LeaveException

class EmployeeLeaveData:
    def __init__(self, id, email, name, leaves_left):
        self.id = id
        self.email = email
        self.name = name
        self.leaves_left = leaves_left

    def validate_data(self):
        # raise the exception if leaves left are less than 2
        if self.leaves_left < 2:
            raise LeaveException(
                'Leave Balance for Employee {}-{} is less than minimum threshold.'.format(self.id, self.name))
        else:
            print('Leaves for Employee {}-{} are more than minimum threshold.'.format(self.id, self.name))


try:
    emp1 = EmployeeLeaveData(1231, '[email protected]', 'John Deol', 5)
    emp1.validate_data()
    emp2 = EmployeeLeaveData(1232, '[email protected]', 'Sunny Deol', 1)
    emp2.validate_data()
except LeaveException as l:
    print(l)

O/P

Leaves for Employee 1231-John Deol are more than minimum threshold.
XXXXXXXXXXXX LEAVE EXCEPTION RAISED XXXXXXXXXXXX
Leave Balance for Employee 1232-Sunny Deol is less than minimum threshold.

So, now we have created our own custom exception for our own purpose. Hope it was helpful tutorial for you.

NEXT TUTORIAL >> File Handling in Python





Tags: assert with custom exception pythoncustom exception best practices pythoncustom exception class in pythoncustom exception examplecustom exception handling in pythoncustom exception in pythoncustom exception in python w3schoolscustom exception logging pythoncustom exception meaningcustom exception python 3custom exception python messagecustom exception type pythonhow to create user defined exception in pythonhow to custom exception in pythonhow to handle custom exception in pythonjava custom checked exception examplepython create exception from exceptionpython declare custom typepython raise custom exception examplepython raise exception empty listpython raise exception examplepython raise exception vs returnpython raise vs raise exceptionuser defined exception in python exampleuser defined exception in python javatpointwhat are the 3 major exception types in pythonwhat is custom exception in pythonwhat is except exception in pythonwhat is user defined exception in pythonwhy we need custom exception in java
  • Previous File Handling in Python with example
  • Next Types of Exceptions in Python with Examples

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Advertise with us

Table of Content – Python

  1. Introduction to Python ▼
    • Python and its features
    • Key Differences : C vs Python
    • Key Differences : Java vs Python
    • Python Flavors
    • PVM and Memory Management in Python

  2. Python Fundamentals ▼
    • 'Hello World' using Python
    • Comments in Python
    • Variables and Garbage Collection in Python
    • Datatypes in Python
    • Determining the Datatype of Literal | type() method
    • Tokens in Python
    • Keywords in Python
    • Identifiers and Naming Convention in Python
    • Literals in Python

  3. Python Operators ▼
    • Operators in Python
    • Python Mathematical Functions

  4. Python User Inputs ▼
    • Taking Inputs | input() function in Python

  5. Python Control Statements ▼
    • Control Statements in Python
    • if-elif-else Statements in Python
    • Looping in Python
    • while loop in Python
    • while-else loop in Python
    • for loop in Python
    • for-else loop in Python
    • Infinite loops in Python
    • Nested loops in Python
    • break Statement in Python
    • continue Statement in Python
    • pass Statement in Python
    • assert Statement in Python
    • return Statement in Python

  6. Python Functions ▼
    • Introduction to Python Functions
    • Python Functions vs Python Methods
    • Local and Global Variables in Python
    • Formal and Actual Arguments in Python
    • Recursion in Python Functions
    • Lambda Functions in Python
    • Function Decorators in Python
    • Function Generators in Python

  7. Python Strings ▼
    • Strings in Python and Basic Operations
    • String Immutability Explained
    • strip() method in Strings
    • find() method in Strings
    • count() method in Strings
    • replace() method in Strings
    • split() method in Strings
    • Switching Cases in Strings
    • startswith() method in Strings
    • endswith() method in Strings

  8. Python Lists ▼
    • Python Lists Basics
    • index() method in list
    • append() method in list
    • insert() method in list
    • copy() method in list
    • remove() method in list
    • pop() method in list
    • sort() method in list
    • reverse() method in list
    • clear() method in list
    • Nested Lists in Python
    • List Comprehensions in Python

  9. Python Sets ▼
    • Python Sets and Basic Operations
    • Adding Elements in Python Sets
    • Removing Elements in Python Sets
    • Union in Python Sets
    • Intersection in Python Sets

  10. Python Tuples ▼
    • Python Tuple Basics
    • Python Tuples Immutability Explained
    • Python Tuples Methods
    • Python Nested Tuples

  11. Python Dictionary ▼
    • Python Dictionary Basics
    • Python Dictionary Sorting
    • Python Dictionary List to Dictionary Conversion
    • Passing Dictionary to Function

  12. Python Classes and Objects ▼
    • Classes and Objects
    • self variable in Python
    • __init__() method in Python
    • Inner Classes
    • Instance variable and methods
    • Class variable and methods

  13. Python OOPs ▼
    • Inheritance and its types
    • super() method in Python
    • Abstract class| Abstract method in Python

  14. Python Exception Handling ▼
    • Errors in Python and its types
    • Exception Handling in Python
    • Types of Exceptions in Python
    • Custom Exceptions in Python

  15. Python File Handling ▼
    • File Handling in Python
    • with statement in Python

  16. Python DateTime Modules ▼
    • datetime module in Python

  17. Python MultiThreading ▼
    • Multithreading in Python

  18. Python Requests Module ▼
    • Python GET Request
    • Python POST Request
    • Python PUT Request

Python Programs

  1. Fibonacci Series till 'N' Numbers

  2. Sum of Digits of a Number

  3. Checking Prime Number

  4. Checking Armstrong Number

  5. Finding Reverse Number (Traditional)

  6. Finding Reverse Number (Pythonic)

  7. Finding Prime Numbers within Range

  8. Finding Prime Numbers within Range Using SOE

  9. Checking Leap year

  10. Calculating Simple Interest

  11. Generate Random Numbers

  12. Calculate Compound Interest

  13. Area of Circle

  14. ASCII Value of Character
CODE OF GEEKS

Subscribe to Newsletter

CODE OF GEEKS

Learn | Code | Achieve

Reach us

[email protected]
We at CODE OF GEEKS, aim at providing quality content to our users at no cost.
CODE OF GEEKS

Important Pages

About us
Advertise
Privacy Policy
Terms and Conditions
Refund Policy
Contact us

Placements – Study Materials

TCS NQT     Wipro     CapGemini
Accenture     MindTree     CTS
DXC     Hexaware Technologies     AMCAT
CoCubes     Goldman Sachs     Dell
Cisco     Deloitte     Virtusa     LTI     Infosys   

Tutorials

Python
Node.js
Express.js
Golang

Recent Posts

Strings in Go and its basic operations
  • August 11, 2023
Introduction to Functions in Go programming
  • August 11, 2023

Copyright @ CODE OF GEEKS. All Rights Reserved.