Try–catch block in C++ - Time & Space Complexity
We want to understand how using a try-catch block affects the time it takes for a program to run.
Specifically, does catching errors change how long the program works as the input grows?
Analyze the time complexity of the following code snippet.
try {
for (int i = 0; i < n; i++) {
// some operation
}
} catch (const std::exception &e) {
std::cout << "Error caught" << std::endl;
}
This code tries to run a loop n times and catches any exceptions that happen.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop running n times.
- How many times: Exactly n times, once for each loop cycle.
As n grows, the loop runs more times, so the work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop operations |
| 100 | About 100 loop operations |
| 1000 | About 1000 loop operations |
Pattern observation: The work grows in a straight line as n increases.
Time Complexity: O(n)
This means the time to run grows directly with the size of the input n.
[X] Wrong: "The try-catch block makes the code slower for every loop cycle."
[OK] Correct: The try-catch block itself does not slow down the loop unless an exception actually happens. Normal execution runs at the same speed.
Understanding how error handling affects performance helps you write reliable code without guessing about speed. This skill shows you think about both correctness and efficiency.
"What if the code inside the try block threw an exception every time? How would that affect the time complexity?"
Practice
What is the main purpose of a try-catch block in C++?
Solution
Step 1: Understand the role of try block
Thetryblock contains code that might cause an error or exception.Step 2: Understand the role of catch block
Thecatchblock handles the error so the program does not crash.Final Answer:
To handle errors and exceptions safely during program execution -> Option AQuick Check:
Try-catch handles errors = B [OK]
- Thinking try-catch speeds up code
- Confusing try-catch with loops
- Using try-catch to declare variables
Which of the following is the correct syntax to start a try block in C++?
?
Solution
Step 1: Recall try block syntax
Thetryblock starts with the keywordtryfollowed by curly braces{ }.Step 2: Identify correct option
Only try { usestry {which is correct syntax to start the block.Final Answer:
try { -> Option DQuick Check:
Try block starts with try { = C [OK]
- Using parentheses instead of curly braces
- Starting with catch instead of try
- Using colon after try
What will be the output of the following C++ code?
try {
int x = 5 / 0;
std::cout << "Result: " << x << std::endl;
} catch (const std::exception& e) {
std::cout << "Caught exception" << std::endl;
}Solution
Step 1: Analyze division by zero in C++
Integer division by zero causes undefined behavior and usually crashes the program; it does not throw a standard exception.Step 2: Check catch block type
The catch block catchesstd::exceptiontypes, but division by zero does not throw this exception automatically.Final Answer:
Program crashes with division by zero error -> Option CQuick Check:
Integer division by zero crashes = D [OK]
- Assuming catch block catches all errors
- Expecting output 'Caught exception'
- Thinking division by zero returns zero
Identify the error in this C++ code snippet:
try {
throw 10;
} catch (int e) {
std::cout << "Caught int: " << e << std::endl;
} catch (...) {
std::cout << "Caught unknown" << std::endl;
}Solution
Step 1: Check throw and catch types
The code throws an int and catches it withcatch(int e), which matches correctly.Step 2: Verify catch block order
The specific catchcatch(int e)comes before the catch-allcatch(...), which is correct.Final Answer:
No error; code is correct -> Option BQuick Check:
Throw int caught by int catch first = A [OK]
- Placing catch(...) before specific catch
- Thinking multiple catch blocks are invalid
- Believing throwing int is not allowed
Consider this code snippet:
try {
std::string s = "hello";
int n = std::stoi(s);
std::cout << n << std::endl;
} catch (const std::invalid_argument& e) {
std::cout << "Invalid argument caught" << std::endl;
} catch (...) {
std::cout << "Other exception caught" << std::endl;
}What will be the output and why?
Solution
Step 1: Understand std::stoi behavior
Trying to convert "hello" to int usingstd::stoithrowsstd::invalid_argumentexception because "hello" is not a number.Step 2: Check catch blocks
The first catch block catchesstd::invalid_argumentexceptions and prints "Invalid argument caught".Final Answer:
Invalid argument caught -> Option AQuick Check:
std::stoi throws invalid_argument for non-numeric string = A [OK]
- Expecting program to print 'hello'
- Assuming catch(...) runs instead of specific catch
- Thinking program crashes without catch
Ready to prove it?
Pass the test and this pattern moves unknown
