A try-catch block helps your program handle errors without crashing. It lets you try some code and catch problems if they happen.
Try–catch block in C++
try { // code that might cause an error } catch (const ExceptionType& e) { // code to handle the error }
try { int x = std::stoi("abc"); } catch (const std::exception& e) { std::cout << "Error: " << e.what() << std::endl; }
try { throw std::runtime_error("Oops!"); } catch (const std::runtime_error& e) { std::cout << "Caught: " << e.what() << std::endl; }
This program tries to divide 5 by 0. It throws an error and catches it to print a friendly message instead of crashing.
#include <iostream> #include <stdexcept> int main() { try { int a = 5; int b = 0; if (b == 0) { throw std::runtime_error("Cannot divide by zero"); } int c = a / b; std::cout << "Result: " << c << std::endl; } catch (const std::runtime_error& e) { std::cout << "Error caught: " << e.what() << std::endl; } return 0; }
Always catch exceptions by reference to avoid slicing.
You can have multiple catch blocks for different error types.
If no catch matches, the program will terminate.
Try-catch blocks help handle errors safely.
Put risky code inside try and handle errors in catch.
This keeps your program running smoothly even when problems happen.
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
