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
Creating exception classes
📖 Scenario: Imagine you are building a simple banking system. You want to handle errors like when someone tries to withdraw more money than they have.
🎯 Goal: You will create a custom exception class called InsufficientFundsError to handle this specific error. Then you will use it in a function that withdraws money from an account.
📋 What You'll Learn
Create a custom exception class named InsufficientFundsError that inherits from Exception.
Create a variable balance with the value 100.
Create a variable withdraw_amount with the value 150.
Write a function withdraw that takes amount as a parameter.
Inside the function, raise InsufficientFundsError with the message 'Not enough money in the account' if amount is greater than balance.
Call the withdraw function with withdraw_amount inside a try block.
Catch the InsufficientFundsError exception and print its message.
💡 Why This Matters
🌍 Real World
Custom exceptions help you handle specific errors in your programs clearly, like when a bank account has insufficient funds.
💼 Career
Knowing how to create and use custom exceptions is important for writing robust software that handles errors gracefully in real-world applications.
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 add pass inside.
2
Set up 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
Use simple assignment like balance = 100 and withdraw_amount = 150.
3
Write the withdraw function with exception
Write a function called withdraw that takes a parameter amount. Inside the function, if amount is greater than balance, raise InsufficientFundsError with the message 'Not enough money in the account'.
Python
Hint
Use def withdraw(amount): and inside check if amount > balance: then raise InsufficientFundsError('Not enough money in the account').
4
Call withdraw and handle exception
Call the withdraw function with withdraw_amount inside a try block. Catch the InsufficientFundsError exception and print its message.
Python
Hint
Use try: to call withdraw(withdraw_amount) and except InsufficientFundsError as e: to print e.
Practice
(1/5)
1. What is the correct way to create a custom exception class in Python?
easy
A. exception MyError(Exception): pass
B. def MyError(): raise Exception
C. class MyError(Exception): pass
D. class MyError: pass
Solution
Step 1: Understand how to define a class inheriting Exception
Custom exceptions must inherit from the built-in Exception class to behave like errors.
Step 2: Check syntax correctness
class MyError(Exception): pass correctly defines a class named MyError inheriting from Exception with pass inside.
Final Answer:
class MyError(Exception): pass -> Option C
Quick Check:
Custom exception class = class MyError(Exception): pass [OK]
Hint: Inherit from Exception to create custom errors [OK]
Common Mistakes:
Not inheriting from Exception
Using def instead of class
Wrong keyword like 'exception' instead of 'class'
2. Which of the following is the correct syntax to raise a custom exception named MyError?
easy
A. raise MyError()
B. throw MyError()
C. raise new MyError()
D. throw new MyError()
Solution
Step 1: Recall the Python keyword to raise exceptions
Python uses the keyword 'raise' to trigger exceptions, not 'throw'.
Step 2: Check the syntax for raising a custom exception
Correct syntax is 'raise MyError()' to create and raise the exception instance.
Final Answer:
raise MyError() -> Option A
Quick Check:
Raise custom error = raise MyError() [OK]
Hint: Use 'raise' keyword followed by exception instance [OK]
Common Mistakes:
Using 'throw' instead of 'raise'
Adding 'new' keyword like in other languages
Not calling the exception as a function
3. What will be the output of this code?
class MyError(Exception):
pass
try:
raise MyError("Oops!")
except MyError as e:
print(e)
medium
A. Oops!
B. MyError
C. Exception
D. No output
Solution
Step 1: Understand the raise statement with message
The code raises MyError with the message 'Oops!'.
Step 2: Catch the exception and print its message
The except block catches MyError as 'e' and prints 'e', which outputs the message 'Oops!'.
Final Answer:
Oops! -> Option A
Quick Check:
Exception message prints = Oops! [OK]
Hint: Exception instance prints its message string [OK]
Common Mistakes:
Printing exception class name instead of message
Not catching the exception properly
Expecting no output
4. Identify the error in this code snippet:
class MyError(Exception):
pass
try:
raise MyError
except MyError:
print("Caught error")
medium
A. Incorrect exception name in except block
B. No error, code runs fine
C. Syntax error in class definition
D. Missing parentheses when raising MyError
Solution
Step 1: Check how the exception is raised
In Python, it is valid to raise an exception class without parentheses if it has no __init__ arguments.
Step 2: Identify the problem in the code
The code uses 'raise MyError' without parentheses, which is valid and does not raise an error.
Final Answer:
No error, code runs fine -> Option B
Quick Check:
Raising exception class without parentheses is allowed [OK]
Hint: Raising exception class without parentheses is valid if no arguments [OK]
Common Mistakes:
Omitting parentheses after exception name
Mismatching exception names in except block
Incorrect class syntax
5. You want to create a custom exception ValidationError that stores an error code along with the message. Which code correctly implements this?
hard
A. class ValidationError(Exception):
def __init__(self, message):
self.code = 0
super().__init__(message)
B. class ValidationError(Exception):
def __init__(self, message, code):
self.message = message
self.code = code
C. class ValidationError(Exception):
def __init__(self, code):
super().__init__(code)
D. class ValidationError(Exception):
def __init__(self, message, code):
super().__init__(message)
self.code = code
Solution
Step 1: Understand how to extend Exception with extra attributes
To add an error code, override __init__ and call super().__init__(message) to set the message properly.
Step 2: Check which option correctly calls super().__init__ and stores code
class ValidationError(Exception):
def __init__(self, message, code):
super().__init__(message)
self.code = code calls super().__init__(message) and assigns self.code = code, correctly storing both.
Final Answer:
class ValidationError(Exception):
def __init__(self, message, code):
super().__init__(message)
self.code = code -> Option D
Quick Check:
Call super().__init__(message) and store extra attributes [OK]
Hint: Call super().__init__(message) to set message, then add code [OK]