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?"
Practice
throw keyword do in C++?Solution
Step 1: Understand the purpose of
Thethrowthrowkeyword is used to signal that an error or exceptional condition has occurred in the program.Step 2: Differentiate from other keywords
throwdoes not catch exceptions (that'scatch), nor does it define functions or declare variables.Final Answer:
It signals an error by raising an exception. -> Option CQuick Check:
throw= signal error [OK]
- Confusing throw with catch
- Thinking throw declares variables
- Assuming throw defines functions
Solution
Step 1: Recall correct throw syntax
In C++, to throw an exception, you usethrowfollowed by the value or object, without parentheses or type keywords.Step 2: Analyze each option
throw 10; usesthrow 10;which is correct. throw(int 10); incorrectly declares a type inside parentheses, invalid syntax. throw int 10; incorrectly adds type keyword. throw new int(10); throws a pointer, which is allowed but not the simplest form here.Final Answer:
throw 10; -> Option DQuick Check:
Simple throw syntax =throw value;[OK]
- Adding parentheses after throw
- Including type keyword with throw
- Throwing pointers when not needed
try {
throw "Error occurred";
} catch (const char* msg) {
std::cout << msg << std::endl;
}Solution
Step 1: Understand the throw and catch block
The code throws a string literal "Error occurred" and catches it as aconst char*pointer.Step 2: Check the catch block output
The catch block prints the caught message usingstd::cout, so it will output the string "Error occurred" followed by a newline.Final Answer:
Error occurred -> Option AQuick Check:
Thrown string caught and printed = "Error occurred" [OK]
- Expecting compilation error due to throw
- Thinking catch won't match string literal
- Assuming no output without explicit return
try {
throw 5;
} catch (int e) {
std::cout << "Caught: " << e << std::endl;
} catch (...) {
std::cout << "Unknown exception" << std::endl;
}Solution
Step 1: Analyze the try and catch blocks
The code throws an integer 5, which is caught by the first catch block forint. The second catch block is a catch-all for any other exceptions.Step 2: Check for syntax or logic errors
Multiple catch blocks are allowed and correctly ordered from specific to general. The catch blocks have correct parameter types. Throwing an int matches the first catch.Final Answer:
No error, code is correct -> Option AQuick Check:
Proper catch blocks for thrown int = correct code [OK]
- Thinking multiple catch blocks cause error
- Missing parameter type in catch
- Throwing incompatible data type
checkValue and print a message for each type accordingly?Solution
Step 1: Identify exception types thrown
The function throws three different types:std::string,int, anddouble.Step 2: Determine how to catch each type
To handle each exception properly, separate catch blocks for each type are needed. Using onlycatch(...)catches all but cannot distinguish types. Catching onlyintmisses others. No catch block causes program termination on exception.Final Answer:
Use separate catch blocks for std::string, int, and double types. -> Option BQuick Check:
Multiple catch blocks for different types = best practice [OK]
- Using only catch(...) and missing type info
- Catching only one exception type
- Not using any catch block
Ready to prove it?
Pass the test and this pattern moves unknown
