0
0
Pythonprogramming~5 mins

Custom error messages in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom error messages
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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

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

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
10About 10 calls to divide_numbers
100About 100 calls to divide_numbers
1000About 999 calls to divide_numbers

Pattern observation: The number of operations grows directly with the input size; doubling input doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows in a straight line as the input size grows.

Common Mistake

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

Interview Connect

Understanding how error handling affects performance shows you can write clear and efficient code, a skill valued in real projects.

Self-Check

"What if we changed the loop to run inside another loop of the same size? How would the time complexity change?"