0
0
PythonHow-ToBeginner · 3 min read

How to Create Custom Exception in Python: Simple Guide

To create a custom exception in Python, define a new class that inherits from Exception or one of its subclasses. Then, you can raise this custom exception using the raise keyword to signal specific error conditions in your code.
📐

Syntax

To create a custom exception, define a class that inherits from Exception. You can add an __init__ method to accept custom error messages or data.

  • class CustomError(Exception): defines the new exception class.
  • def __init__(self, message): initializes the error message.
  • super().__init__(message) calls the base class constructor to set the message.
python
class CustomError(Exception):
    def __init__(self, message):
        super().__init__(message)
💻

Example

This example shows how to define a custom exception and raise it when a condition is met. It also demonstrates catching the custom exception to handle it gracefully.

python
class NegativeNumberError(Exception):
    def __init__(self, message):
        super().__init__(message)


def check_positive(number):
    if number < 0:
        raise NegativeNumberError(f"Negative number not allowed: {number}")
    return number

try:
    check_positive(-5)
except NegativeNumberError as e:
    print(f"Caught an error: {e}")
Output
Caught an error: Negative number not allowed: -5
⚠️

Common Pitfalls

Common mistakes when creating custom exceptions include:

  • Not inheriting from Exception or its subclasses, which can cause unexpected behavior.
  • Failing to call super().__init__() in the constructor, so the error message is not set properly.
  • Using bare except: clauses that catch all exceptions, hiding your custom exceptions.
python
class BadError:
    pass  # Missing inheritance from Exception

class GoodError(Exception):
    def __init__(self, message):
        super().__init__(message)

try:
    raise GoodError("This is a good custom error")
except GoodError as e:
    print(e)
Output
This is a good custom error
📊

Quick Reference

StepDescription
Define classCreate a class inheriting from Exception
Add __init__Optionally add constructor to accept message
Call super()Use super().__init__(message) to set error message
Raise exceptionUse raise CustomException('message') to trigger
Catch exceptionUse try-except to handle your custom exception

Key Takeaways

Always inherit your custom exception class from Exception or its subclasses.
Use super().__init__(message) in your constructor to set the error message correctly.
Raise your custom exception with the raise keyword to signal errors.
Catch your custom exceptions specifically to handle them properly.
Avoid bare except clauses to prevent hiding your custom exceptions.