Throwing exceptions in C++ - Time & Space Complexity
When a program throws an exception, it changes the normal flow of execution. We want to understand how this affects the time it takes for the program to run.
Specifically, we ask: How does throwing an exception impact the number of steps the program takes?
Analyze the time complexity of the following code snippet.
void process(int n) {
for (int i = 0; i < n; i++) {
if (i == 5) {
throw std::runtime_error("Error at 5");
}
// some simple operation
}
}
This code loops from 0 to n-1 but throws an exception when i reaches 5, stopping the loop early.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop running from 0 to n-1.
- How many times: Normally n times, but here it stops early at i = 5 due to the exception.
Because the exception stops the loop early, the number of steps does not grow with n beyond a small fixed number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 6 (loop runs until i=5) |
| 100 | 6 (still stops at i=5) |
| 1000 | 6 (same early stop) |
Pattern observation: The execution steps stay about the same no matter how big n gets because the exception stops the loop early.
Time Complexity: O(1)
This means the program runs in constant time because it stops after a fixed number of steps regardless of input size.
[X] Wrong: "Throwing an exception always makes the program run slower proportional to input size."
[OK] Correct: In this example, the exception stops the loop early, so the program actually does less work as input grows.
Understanding how exceptions affect program flow helps you explain performance clearly and shows you can think about real-world code behavior beyond just loops.
"What if the exception was thrown only after the loop finishes? How would the time complexity change?"