Skip to content
Home » User defined exceptions in Python

User defined exceptions in Python


User-Defined Exceptions in Python

Python comes with many built-in exceptions (like ValueError, TypeError, etc.).
However, sometimes we may need to handle custom errors specific to an application.

For such cases, Python allows us to create our own exceptions.

These are called User-Defined Exceptions or Custom Exceptions.


Definition (Exam Answer)

A user-defined exception is a custom exception created by the programmer by inheriting from Python’s built-in Exception class. It is used when built-in exceptions are not suitable to handle specific errors in a program.


How to Create a User-Defined Exception?

Steps:

  1. Create a class
  2. Inherit it from Exception
  3. Use raise to throw the exception
  4. Handle it with try-except

Basic Example of User-Defined Exception

class MyError(Exception):
    pass

try:
    raise MyError("This is a custom error!")
except MyError as e:
    print("Caught:", e)

Output:

Caught: This is a custom error!

Creating Custom Validation Exceptions (Important for Exams)

Example: Age Validation

class AgeError(Exception):
    pass

try:
    age = int(input("Enter age: "))
    if age < 0:
        raise AgeError("Age cannot be negative!")
    print("Age is valid")
except AgeError as e:
    print("Error:", e)

Example: Bank Minimum Balance Exception

class MinimumBalanceError(Exception):
    pass

try:
    balance = 1000
    withdraw = 1500
    
    if withdraw > balance:
        raise MinimumBalanceError("Insufficient balance!")
    else:
        balance -= withdraw
except MinimumBalanceError as e:
    print("Transaction failed:", e)

User-Defined Exception with Custom Attributes

You can pass custom values to your exception:

class MarksError(Exception):
    def __init__(self, marks):
        self.marks = marks
        super().__init__("Invalid Marks")

try:
    m = 150
    if m > 100:
        raise MarksError(m)
except MarksError as e:
    print(e, "- You entered:", e.marks)

Why Do We Need User-Defined Exceptions?

✔ Built-in exceptions may not cover all error types
✔ Helps in creating meaningful error messages
✔ Useful for validating data (age, marks, balance, input)
✔ Makes code more structured and readable
✔ Helps implement application-specific rules


Advantages of Custom Exceptions

AdvantageExplanation
More clarityGives exact error reason
Better error handlingSpecific to the application
Improves robustnessCode becomes more reliable
Easy debuggingCustom messages help track problems

Exam-Oriented Summary

  • User-defined exceptions allow programmers to define their own error types
  • Created using class MyError(Exception): syntax
  • Raised using the raise statement
  • Handled using try-except blocks
  • Useful when built-in exceptions are insufficient

Short Answer for Exam

User-defined exceptions are custom exceptions created by inheriting from the built-in Exception class. They allow programmers to handle application-specific errors using raise and try-except.