0
0
Pythonprogramming~5 mins

Extending built-in exceptions in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extending built-in exceptions
O(n)
Understanding Time Complexity

When we extend built-in exceptions in Python, we add custom behavior to error handling.

We want to see how the time to create and raise these exceptions changes as input grows.

Scenario Under Consideration

Analyze the time complexity of this custom exception class and its usage.


class MyError(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code


def check_value(x):
    if x < 0:
        raise MyError('Negative value', x)
    return x
    

This code defines a new error type and raises it when a value is negative.

Identify Repeating Operations

Look for loops or repeated actions that affect time.

  • Primary operation: Creating and raising the custom exception.
  • How many times: Once per call to check_value when input is negative.
How Execution Grows With Input

Each call to check_value does a simple check and may raise an exception.

Input Size (n)Approx. Operations
1010 checks, few exceptions if any
100100 checks, exceptions only when input is negative
10001000 checks, exceptions rare or frequent based on input

Pattern observation: Time grows linearly with number of calls, exception creation cost is constant per raise.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly with how many times you call the function, since each call does a simple check.

Common Mistake

[X] Wrong: "Creating a custom exception makes the program slower exponentially."

[OK] Correct: Creating and raising exceptions takes constant time each time, so it does not grow exponentially with input size.

Interview Connect

Understanding how custom exceptions affect performance helps you write clear and efficient error handling in real projects.

Self-Check

What if the exception included a large data structure as a property? How would the time complexity change?