0
0
Pythonprogramming~5 mins

Generic exception handling in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Generic exception handling
O(1)
Understanding Time Complexity

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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n grows, the loop tries more divisions, but the first error stops the loop.

Input Size (n)Approx. Operations
10About 1 operation before error (division by zero)
100Still about 1 operation before error
1000Still about 1 operation before error

Pattern observation: The loop stops early due to the error, so operations do not grow with n.

Final Time Complexity

Time Complexity: O(1)

This means the program runs in constant time because the error stops the loop quickly.

Common Mistake

[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.

Interview Connect

Understanding how exceptions affect program flow and time helps you write better, more predictable code.

Self-Check

"What if the exception was handled inside the loop instead of outside? How would the time complexity change?"