Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Why Custom Exceptions Are Needed
📖 Scenario: Imagine you are building a simple banking app. You want to handle errors like trying to withdraw more money than the account has. Python has built-in errors, but sometimes you want to create your own special error messages that make it clear what went wrong in your app.
🎯 Goal: You will create a custom exception called InsufficientFundsError to show a clear message when someone tries to take out too much money from their bank account.
📋 What You'll Learn
Create a custom exception class called InsufficientFundsError that inherits from Exception.
Create a variable balance with the value 100.
Create a variable withdraw_amount with the value 150.
Write an if statement to check if withdraw_amount is greater than balance.
If it is, raise the InsufficientFundsError with the message 'Not enough money in your account.'.
If not, subtract withdraw_amount from balance.
Print the remaining balance.
💡 Why This Matters
🌍 Real World
Custom exceptions are used in real apps to give clear error messages that help users and developers understand problems quickly.
💼 Career
Knowing how to create and use custom exceptions is important for writing clean, maintainable code in software development jobs.
Progress0 / 4 steps
1
Create the custom exception class
Create a custom exception class called InsufficientFundsError that inherits from Exception.
Python
Hint
Use class InsufficientFundsError(Exception): and inside write pass.
2
Set up the balance and withdraw amount
Create a variable called balance and set it to 100. Then create a variable called withdraw_amount and set it to 150.
Python
Hint
Write balance = 100 and withdraw_amount = 150.
3
Check if withdrawal is possible and raise exception
Write an if statement to check if withdraw_amount is greater than balance. If it is, raise the InsufficientFundsError with the message 'Not enough money in your account.'. Otherwise, subtract withdraw_amount from balance.
Python
Hint
Use if withdraw_amount > balance: then raise InsufficientFundsError('Not enough money in your account.'). Else subtract.
4
Print the remaining balance
Write print(balance) to display the remaining balance after the withdrawal check.
Python
Hint
Just write print(balance). But since withdrawal is too big, the program will raise the custom error instead of printing.
Practice
(1/5)
1. Why do programmers create custom exceptions instead of using only built-in exceptions?
easy
A. To clearly identify and handle specific errors unique to their program
B. Because built-in exceptions are slower to execute
C. To avoid writing any error handling code
D. Because Python does not have any built-in exceptions
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 A
Quick 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
A. def MyError(): pass
B. class MyError(Exception): pass
C. class MyError: pass
D. exception MyError(Exception): pass
Solution
Step 1: Recall syntax for custom exceptions
Custom exceptions are classes that inherit from Exception or its subclasses.
Step 2: Identify correct class definition
class MyError(Exception): pass correctly defines MyError as a subclass of Exception with pass to keep it simple.
Final Answer:
class MyError(Exception): pass -> Option B
Quick 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
A. Negative value
B. -1
C. None
D. No output
Solution
Step 1: Analyze function behavior
The function test raises MyError with message "Negative value" if input is less than 0.
Step 2: Trace try-except block
Calling test(-1) raises MyError. The except block catches it and prints the error message.
Final Answer:
Negative value -> Option A
Quick 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
A. Custom exception must not inherit Exception
B. except block should catch MyError, not Exception
C. raise keyword is missing
D. Using e.message to get error text causes AttributeError
Solution
Step 1: Check exception message access
In Python, exception objects do not have a message attribute by default.
Step 2: Identify correct way to get message
The message is accessed by converting the exception to string or using args. Using e.message causes an AttributeError.
Final Answer:
Using e.message to get error text causes AttributeError -> Option D
Quick Check:
Exception message accessed via str(e), not e.message [OK]
Hint: Use str(e) to get exception message, not e.message [OK]
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
A. Print error message instead of raising exceptions
B. Use only built-in ValueError without custom exceptions
C. Define InvalidAgeError inheriting Exception, raise it in a function checking age limits
D. Catch all exceptions with a generic except block without custom exceptions
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
Defining InvalidAgeError inheriting 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 C
Quick Check:
Custom exception for specific validation error [OK]
Hint: Raise custom exceptions for clear, specific validation errors [OK]