Generic exception handling in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we use generic exception handling in Python, it can affect how long our program takes to run.
We want to see how the time to handle errors grows as the program runs.
Analyze the time complexity of the following code snippet.
try:
for i in range(n):
print(10 // i)
except Exception:
print("Error occurred")
This code tries to divide 10 by numbers from 0 to n-1 and catches any error that happens.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs from 0 to n-1.
- How many times: It repeats n times, but an exception may stop it early.
As n grows, the loop tries more divisions, but the first error stops the loop.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 operation before error (division by zero) |
| 100 | Still about 1 operation before error |
| 1000 | Still about 1 operation before error |
Pattern observation: The loop stops early due to the error, so operations do not grow with n.
Time Complexity: O(1)
This means the program runs in constant time because the error stops the loop quickly.
[X] Wrong: "The loop always runs n times even with exception handling."
[OK] Correct: The exception stops the loop early, so it does not always run fully.
Understanding how exceptions affect program flow and time helps you write better, more predictable code.
"What if the exception was handled inside the loop instead of outside? How would the time complexity change?"
Practice
except Exception do in Python?Solution
Step 1: Understand the role of
This clause catches exceptions that are instances of the Exception class or its subclasses, which covers most runtime errors.except ExceptionStep 2: Recognize its effect on program flow
By catching these exceptions, the program avoids crashing and can handle errors gracefully.Final Answer:
It catches most types of errors to prevent the program from crashing. -> Option CQuick Check:
Generic exception handling = catches most errors [OK]
except Exception to stop crashes [OK]- Thinking it only catches syntax errors
- Believing it fixes errors automatically
- Assuming it ignores errors silently
Solution
Step 1: Identify correct exception syntax
In Python, to catch most exceptions, useexcept Exception:. The bareexcept:also catches exceptions but is less specific.Step 2: Check syntax correctness
try: pass except Exception: uses the correct keywordexceptwith the Exception class, which is the recommended way.Final Answer:
try:\n pass\nexcept Exception: -> Option DQuick Check:
Correct generic catch syntax = except Exception: [OK]
except Exception: to catch most errors correctly [OK]- Using
catchinstead ofexcept - Using undefined
Errorclass - Using bare except without colon
try:
x = 5 / 0
except Exception:
print("Error caught")
print("Done")Solution
Step 1: Identify the error raised
The code tries to divide 5 by 0, which raises a ZeroDivisionError, a subclass of Exception.Step 2: Check exception handling and output
Theexcept Exceptionblock catches this error and prints "Error caught". Then the program continues and prints "Done".Final Answer:
Error caught\nDone -> Option BQuick Check:
ZeroDivisionError caught = prints error message and continues [OK]
- Expecting program to crash with error message
- Thinking error message is printed automatically
- Missing that 'Done' prints after exception
try:
print(10 / 0)
except Exception
print("Caught error")Solution
Step 1: Check syntax of except block
The except line is missing a colon at the end, which is required in Python syntax.Step 2: Confirm other parts are correct
Division by zero raises ZeroDivisionError, subclass of Exception, so it is caught. The print statement syntax is correct. Else clause is optional.Final Answer:
Missing colon after except Exception -> Option AQuick Check:
except line must end with colon : [OK]
- Forgetting colon after except
- Thinking division by zero is uncaught
- Believing else clause is mandatory
def safe_divide(a, b):
try:
return a / b
except Exception as e:
print(e)
return NoneSolution
Step 1: Analyze the try-except block
The function tries to divide a by b. If any exception occurs, it is caught byexcept Exception as e.Step 2: Check error message printing and return
The caught exception is printed usingprint(e), then the function returns None to indicate failure.Final Answer:
This code catches all exceptions and prints the error message. -> Option AQuick Check:
except Exception as e prints error message [OK]
except Exception as e to print error details [OK]- Not using 'as e' to access error message
- Assuming only ZeroDivisionError is caught
- Missing return after exception
