Handling specific exceptions in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we handle specific exceptions in Python, we want to know how the program's running time changes as the input grows.
We ask: How does catching errors affect how long the program takes?
Analyze the time complexity of the following code snippet.
def divide_numbers(numbers, divisor):
results = []
for num in numbers:
try:
results.append(num / divisor)
except ZeroDivisionError:
results.append(None)
return results
This code divides each number in a list by a divisor, handling the case when the divisor is zero.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every item in the input list.
As the list gets bigger, the program does more divisions and checks for exceptions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 divisions and checks |
| 100 | About 100 divisions and checks |
| 1000 | About 1000 divisions and checks |
Pattern observation: The work grows directly with the number of items in the list.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[X] Wrong: "Handling exceptions inside the loop makes the program much slower and changes the time complexity."
[OK] Correct: The exception handling adds a small fixed cost per item, but the main time still grows linearly with the list size.
Understanding how exception handling affects time helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we moved the try-except block outside the loop? How would the time complexity change?"
Practice
try-except blocks in Python?Solution
Step 1: Understand the role of try-except
Thetry-exceptblock is used to catch errors that happen during program execution.Step 2: Identify the benefit of catching errors
By catching errors, the program can handle them gracefully and continue running instead of crashing.Final Answer:
To catch and handle specific errors so the program doesn't crash -> Option AQuick Check:
try-except = catch errors [OK]
- Thinking try-except speeds up code
- Confusing try-except with comments
- Believing try-except creates functions
ZeroDivisionError in Python?Solution
Step 1: Check the correct keyword for catching exceptions
Python usesexceptto catch exceptions, notcatch.Step 2: Verify the exception name spelling
The correct exception name isZeroDivisionError, notZeroDivision.Final Answer:
try: x = 1/0 except ZeroDivisionError: print('Cannot divide by zero') -> Option CQuick Check:
Use except + exact exception name [OK]
- Using 'catch' instead of 'except'
- Misspelling exception names
- Using generic except without specifying error
try:
num = int('abc')
except ValueError:
print('Value error caught')
except TypeError:
print('Type error caught')Solution
Step 1: Identify the error raised by int('abc')
Trying to convert 'abc' to int raises aValueError.Step 2: Match the error with except blocks
TheValueErroris caught by the first except block, so it prints 'Value error caught'.Final Answer:
Value error caught -> Option AQuick Check:
int('abc') = ValueError caught [OK]
- Confusing ValueError with TypeError
- Thinking program crashes without except
- Assuming no output if error caught
try:
print(10 / 0)
except ZeroDivisionError, e:
print('Error:', e)Solution
Step 1: Identify the syntax error in except clause
Python 3 requires 'as' to assign exception to a variable, not a comma.Step 2: Correct the except syntax
Replaceexcept ZeroDivisionError, e:withexcept ZeroDivisionError as e:.Final Answer:
Change except line to: except ZeroDivisionError as e: -> Option BQuick Check:
Use 'as' to assign exception variable [OK]
- Using comma instead of 'as' in except
- Removing except block causing crash
- Wrong parentheses in except clause
KeyError and IndexError in the same block. Which is the best way to write the except clause?Solution
Step 1: Understand how to catch multiple exceptions
Python requires a tuple of exceptions inside parentheses to catch multiple exceptions in one block.Step 2: Identify correct tuple syntax
The correct syntax isexcept (KeyError, IndexError):to catch both exceptions.Final Answer:
except (KeyError, IndexError): print('Error caught') -> Option DQuick Check:
Use tuple in except to catch multiple exceptions [OK]
- Using 'or' or 'and' instead of tuple
- Using comma without parentheses
- Trying to catch exceptions separately without blocks
