Custom exceptions help you handle specific problems in your program clearly. They make your code easier to understand and fix when something goes wrong.
Why custom exceptions are needed in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
class MyError(Exception): pass
Custom exceptions usually inherit from the built-in Exception class.
You can add your own messages or data inside the custom exception.
Examples
TooColdError.Python
class TooColdError(Exception): pass
Python
class TooColdError(Exception): def __init__(self, temperature): self.temperature = temperature super().__init__(f"Too cold: {temperature}°C")
Sample Program
This program checks if the temperature is below zero. If yes, it raises a custom error. The error is caught and a clear message is printed.
Python
class TooColdError(Exception): def __init__(self, temperature): self.temperature = temperature super().__init__(f"Too cold: {temperature}°C") def check_temperature(temp): if temp < 0: raise TooColdError(temp) else: print(f"Temperature is fine: {temp}°C") try: check_temperature(-5) except TooColdError as e: print(f"Caught an error: {e}")
Important Notes
Custom exceptions improve code clarity by naming specific problems.
They help separate error handling for different issues.
Always inherit from Exception or its subclasses for best practice.
Summary
Custom exceptions let you handle special errors clearly and separately.
They make your program easier to read and debug.
Use them when you want to show or catch specific problems in your code.
Practice
1. Why do programmers create
custom exceptions instead of using only built-in exceptions?easy
Solution
Step 1: Understand the purpose of exceptions
Exceptions help handle errors during program execution. Built-in exceptions cover common errors.Step 2: Recognize the need for custom exceptions
Custom exceptions let programmers mark and handle errors specific to their program clearly and separately.Final Answer:
To clearly identify and handle specific errors unique to their program -> Option AQuick Check:
Custom exceptions = specific error handling [OK]
Hint: Custom exceptions clarify unique errors in your code [OK]
Common Mistakes:
- Thinking built-in exceptions are slow
- Believing custom exceptions remove need for error handling
- Assuming Python lacks built-in exceptions
2. Which of the following is the correct way to define a custom exception named
MyError in Python?easy
Solution
Step 1: Recall syntax for custom exceptions
Custom exceptions are classes that inherit fromExceptionor its subclasses.Step 2: Identify correct class definition
class MyError(Exception): pass correctly definesMyErroras a subclass ofExceptionwithpassto keep it simple.Final Answer:
class MyError(Exception): pass -> Option BQuick Check:
Custom exception = class inheriting Exception [OK]
Hint: Custom exceptions are classes inheriting Exception [OK]
Common Mistakes:
- Defining exception as a function
- Not inheriting from Exception
- Using wrong keyword like 'exception'
3. What will be the output of this code?
class MyError(Exception):
pass
def test(value):
if value < 0:
raise MyError("Negative value")
return value
try:
print(test(-1))
except MyError as e:
print(e)medium
Solution
Step 1: Analyze function behavior
The functiontestraisesMyErrorwith message "Negative value" if input is less than 0.Step 2: Trace try-except block
Callingtest(-1)raisesMyError. The except block catches it and prints the error message.Final Answer:
Negative value -> Option AQuick Check:
Raised custom exception message printed [OK]
Hint: Raised custom exception prints its message in except block [OK]
Common Mistakes:
- Expecting function to return -1
- Thinking no output occurs
- Confusing exception name with message
4. Find the error in this custom exception usage:
class MyError(Exception):
pass
try:
raise MyError("Oops")
except Exception as e:
print("Error:", e.message)medium
Solution
Step 1: Check exception message access
In Python, exception objects do not have amessageattribute by default.Step 2: Identify correct way to get message
The message is accessed by converting the exception to string or usingargs. Usinge.messagecauses an AttributeError.Final Answer:
Using e.message to get error text causes AttributeError -> Option DQuick Check:
Exception message accessed via str(e), not e.message [OK]
Hint: Use str(e) to get exception message, not e.message [OK]
Common Mistakes:
- Assuming e.message exists
- Thinking custom exceptions can't inherit Exception
- Missing raise keyword
- Believing except must catch only MyError
5. You want to create a custom exception
InvalidAgeError that triggers when age is below 0 or above 120. Which approach best uses custom exceptions to handle this validation?hard
Solution
Step 1: Understand validation needs
Age must be checked for invalid values and a clear error raised if invalid.Step 2: Use custom exception for clarity
DefiningInvalidAgeErrorinheriting from Exception and raising it on invalid age clearly signals this specific error.Step 3: Compare other options
Using only built-in exceptions or printing errors reduces clarity and control. Catching all exceptions generically hides specific issues.Final Answer:
Define InvalidAgeError inheriting Exception, raise it in a function checking age limits -> Option CQuick Check:
Custom exception for specific validation error [OK]
Hint: Raise custom exceptions for clear, specific validation errors [OK]
Common Mistakes:
- Relying only on built-in exceptions
- Printing errors instead of raising
- Using generic except blocks hiding issues
