Skip to content

Python Custom Exception Not Catching Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Python Custom Exception Not Catching Fix. We cover key concepts, practical examples, and best practices.

Custom exceptions in Python are not caught by except blocks when the exception class is defined incorrectly, imported from the wrong module, or does not inherit from Exception. The except clause silently passes or raises an unhandled exception.

The Problem

class MyError:
    """This is not a real exception."""
    pass

try:
    raise MyError()
except MyError:
    print("Caught!")

Error:

TypeError: exceptions must derive from BaseException

Wrong Code

# WRONG — inherits from object, not Exception
class ValidationError:
    pass

def validate(data):
    if not data:
        raise ValidationError("Empty data")

try:
    validate("")
except ValidationError as e:
    print(f"Caught: {e}")

Right Code

class ValidationError(Exception):
    """Custom exception for validation failures."""
    pass

def validate(data):
    if not data:
        raise ValidationError("Data cannot be empty")

try:
    validate("")
except ValidationError as e:
    print(f"Caught: {e}")

Expected output:

Caught: Data cannot be empty

Step-by-Step Fix

Step 1: Always inherit from Exception

# RIGHT
class MyError(Exception):
    pass

# WRONG
class MyError(BaseException):
    pass  # Too broad — includes SystemExit, KeyboardInterrupt

Step 2: Add custom attributes

class APIError(Exception):
    def __init__(self, message, status_code=500):
        super().__init__(message)
        self.status_code = status_code

try:
    raise APIError("Not found", 404)
except APIError as e:
    print(f"Error {e.status_code}: {e}")

Step 3: Catch in the right order

# Specific exceptions before general ones
try:
    result = risky_operation()
except ValueError:
    print("Value error")
except Exception:
    print("General error")

Step 4: Import from the correct module

# exceptions.py
class DatabaseError(Exception):
    pass

# main.py
# WRONG
from exceptions import DatabaseError  # Typo

# RIGHT
from exceptions import DatabaseError

Step 5: Use the correct except syntax

try:
    raise ValidationError("Invalid")
except ValidationError:
    pass  # OK — catches it

try:
    raise ValidationError("Invalid")
except ValidationError as e:
    print(e)  # OK — caught with variable

Step 6: Chain exceptions with raise from

class ProcessingError(Exception):
    pass

try:
    int("not_a_number")
except ValueError as e:
    raise ProcessingError("Failed to process input") from e

Prevention Tips

  • Always inherit from Exception for custom exceptions
  • Place custom exceptions in a dedicated module
  • Use except CustomError as e: to access the exception instance
  • Catch specific exceptions before general ones
  • Test exception raising and catching in unit tests

Common Mistakes with custom exception

  1. Using foldl instead of foldl' causing stack overflow on large lists
  2. Forgetting deriving (Show, Eq) on custom data types needed for debugging
  3. Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable

These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between BaseException and Exception?

BaseException is the root of all exceptions including SystemExit, KeyboardInterrupt, and GeneratorExit. Exception inherits from BaseException and is the base for all non-fatal exceptions. Always inherit from Exception for user-defined exceptions.

Why is my custom exception not caught even though I imported it?

You may have a circular import issue, two different classes with the same name in different modules, or you caught a parent class before the custom exception. Check the import path, and ensure the custom exception is imported in both the raising and catching modules.

Should I include a message in the custom exception constructor?

Yes. Call super().__init__(message) to set the message. This makes str(e) and repr(e) return meaningful information. You can also add custom attributes like status codes, error IDs, or validation details for richer error handling.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro