🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEpython

python Documentation

LOADING ENGINE...

Custom Exceptions

AI & DATA SCIENCE // custom-exceptions

A custom exception is a user-defined class, inheriting from Exception (directly or indirectly), that represents a specific error condition meaningful to your own application.

Syntax

class InsufficientFundsError(Exception):
    pass

raise InsufficientFundsError("Not enough balance")

Deep Dive Course

Defining your own exception class, typically by subclassing Exception with little or no extra code, lets calling code catch exactly the errors your application can produce, distinctly from unrelated built-in exceptions like ValueError or KeyError. A custom exception can also carry extra data beyond just a message, by defining its own __init__ that stores additional attributes, which lets except handlers programmatically inspect what specifically went wrong instead of just parsing an error string.

1Understanding Custom Exceptions

Defining your own exception class, typically by subclassing Exception with little or no extra code, lets calling code catch exactly the errors your application can produce, distinctly from unrelated built-in exceptions like ValueError or KeyError. A custom exception can also carry extra data beyond just a message, by defining its own __init__ that stores additional attributes, which lets except handlers programmatically inspect what specifically went wrong instead of just parsing an error string.

💡

Build a small hierarchy of custom exceptions with one shared base class for your application/library, so callers can either catch a very specific error or catch the shared base class to handle any error from your code broadly.

editor.html
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough balance")
    return balance - amount

try:
    withdraw(50, 100)
except InsufficientFundsError as e:
    print(e)
localhost:3000

2Practical Example

Here is a real-world application of Custom Exceptions showing how it is used in production Python code.

editor.html
class ValidationError(Exception):
    def __init__(self, field, message):
        super().__init__(message)
        self.field = field

try:
    raise ValidationError("email", "Invalid email format")
except ValidationError as e:
    print(f"{e.field}: {e}")
localhost:3000

3Best Practices

Follow these guidelines when working with Custom Exceptions:

1. Subclass Exception, not BaseException directly, for application-specific errors, so they don't accidentally get caught alongside system-exiting exceptions

2. Give custom exceptions clear, specific names ending in 'Error', matching Python's own naming convention

3. Store extra structured data as attributes on the exception instance, not just embedded in the message string, so handlers can inspect it programmatically

⚠️

Tip: Build a small hierarchy of custom exceptions with one shared base class for your application/library, so callers can either catch a very specific error or catch the shared base class to handle any error from your code broadly.

editor.html
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough balance")
    return balance - amount

try:
    withdraw(50, 100)
except InsufficientFundsError as e:
    print(e)
localhost:3000

Examples

Example 01Basic Usage
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough balance")
    return balance - amount

try:
    withdraw(50, 100)
except InsufficientFundsError as e:
    print(e)
Example 02Advanced Example
class ValidationError(Exception):
    def __init__(self, field, message):
        super().__init__(message)
        self.field = field

try:
    raise ValidationError("email", "Invalid email format")
except ValidationError as e:
    print(f"{e.field}: {e}")

Best Practices

  • Subclass Exception, not BaseException directly, for application-specific errors, so they don't accidentally get caught alongside system-exiting exceptions
  • Give custom exceptions clear, specific names ending in 'Error', matching Python's own naming convention
  • Store extra structured data as attributes on the exception instance, not just embedded in the message string, so handlers can inspect it programmatically

Interview Question

Why would you create a custom exception class instead of just raising a built-in one like ValueError with a descriptive message?

Hint: Think about how calling code distinguishes between different error sources.

A custom exception type lets calling code catch precisely the errors your specific application or library can raise, without accidentally also catching unrelated ValueErrors raised by completely different code elsewhere in the program. It also lets you attach structured, application-specific data as attributes on the exception, which a caller can inspect programmatically, rather than having to parse information out of a plain error message string.

Exercises

MediumPractice using Custom Exceptions in a real scenario.
View Solution
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough balance")
    return balance - amount

try:
    withdraw(50, 100)
except InsufficientFundsError as e:
    print(e)

Frequently Asked Questions

Why would you create a custom exception class instead of just raising a built-in one like ValueError with a descriptive message?

A custom exception type lets calling code catch precisely the errors your specific application or library can raise, without accidentally also catching unrelated ValueErrors raised by completely different code elsewhere in the program. It also lets you attach structured, application-specific data as attributes on the exception, which a caller can inspect programmatically, rather than having to parse information out of a plain error message string.

Related Functions

raise-keywordexcept-blockclass-keyword