Python Custom Exception Not Catching Fix
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
Exceptionfor 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
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro