Custom error messages in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we add custom error messages in code, it helps us understand problems better.
We want to see how adding these messages affects how long the program takes to run.
Analyze the time complexity of the following code snippet.
def divide_numbers(a, b):
if b == 0:
raise ValueError("Cannot divide by zero!")
return a / b
for i in range(1, 1000):
try:
result = divide_numbers(10, i - 500)
except ValueError as e:
print(e)
This code tries to divide 10 by numbers from -499 to 499, raising a custom error if dividing by zero.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs 999 times, calling the divide function each time.
- How many times: Exactly 999 times, once per loop iteration.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 calls to divide_numbers |
| 100 | About 100 calls to divide_numbers |
| 1000 | About 999 calls to divide_numbers |
Pattern observation: The number of operations grows directly with the input size; doubling input doubles work.
Time Complexity: O(n)
This means the time it takes grows in a straight line as the input size grows.
[X] Wrong: "Adding custom error messages makes the program much slower because of the extra text."
[OK] Correct: The error message text is just a small part and only runs when an error happens, so it does not change the overall growth with input size.
Understanding how error handling affects performance shows you can write clear and efficient code, a skill valued in real projects.
"What if we changed the loop to run inside another loop of the same size? How would the time complexity change?"
Practice
raise ValueError('Custom message') in Python?Solution
Step 1: Understand the raise statement
Theraisekeyword is used to stop the program and throw an error.Step 2: Purpose of custom messages
Adding a message like'Custom message'helps explain why the error happened.Final Answer:
To stop the program and show a specific error message when a condition is not met. -> Option BQuick Check:
raise with message = stop and explain error [OK]
- Thinking raise only prints messages without stopping
- Confusing raise with print or logging
- Believing raise fixes errors automatically
Solution
Step 1: Identify the correct keyword
In Python,raiseis used to throw errors, notthroworerror.Step 2: Correct order of error and message
The syntax israise ErrorType('message'), so the error type comes first, then the message in parentheses.Final Answer:
raise ValueError('Invalid input') -> Option DQuick Check:
raise + ErrorType('message') = correct syntax [OK]
- Using throw instead of raise
- Placing message before error type
- Missing parentheses around the message
def check_age(age):
if age < 18:
raise ValueError('Age must be 18 or older')
return 'Access granted'
print(check_age(16))Solution
Step 1: Check the condition in the function
The function raises a ValueError if age is less than 18. Here, age is 16, so the error triggers.Step 2: Understand what happens on raise
When the error is raised, the program stops and shows the error message instead of returning 'Access granted'.Final Answer:
ValueError: Age must be 18 or older -> Option CQuick Check:
raise triggers error output = ValueError message [OK]
- Expecting function to return 'Access granted' anyway
- Confusing error message with print output
- Thinking raise prints message but continues
def check_number(num):
if num < 0:
raise 'Negative number error'
return 'Number is positive'
print(check_number(-5))Solution
Step 1: Check the raise statement
The code tries to raise a string directly, which is not allowed in Python. Only Exception types can be raised.Step 2: Correct way to raise errors
Useraise ValueError('message')or another Exception class, not a plain string.Final Answer:
You cannot raise a string directly; it must be an Exception type. -> Option AQuick Check:
raise must use Exception type, not string [OK]
- Raising strings instead of Exception classes
- Forgetting to include parentheses with message
- Changing condition incorrectly
validate_score(score) that raises a ValueError with the message "Score must be between 0 and 100" if the score is outside this range. Which code correctly implements this?Solution
Step 1: Understand the valid range condition
The score is valid if it is between 0 and 100 inclusive. So invalid means less than 0 or greater than 100.Step 2: Check the if condition logic
def validate_score(score): if score < 0 or score > 100: raise ValueError('Score must be between 0 and 100') return 'Valid score' correctly usesif score < 0 or score > 100to detect invalid scores and raise the error.Final Answer:
def validate_score(score): if score < 0 or score > 100: raise ValueError('Score must be between 0 and 100') return 'Valid score' -> Option AQuick Check:
Use or for invalid range, raise error if outside [OK]
- Using and instead of or in condition
- Raising error for valid scores instead of invalid
- Checking only equality instead of range
