What if your program could catch mistakes before they crash everything?
Why Try–catch block in C++? - Purpose & Use Cases
Imagine you are writing a program that reads a file and processes its content. Without any safety checks, if the file is missing or corrupted, your program just crashes suddenly, leaving users confused and frustrated.
Manually checking every possible error before it happens is slow and complicated. You might miss some errors, causing your program to stop unexpectedly. This makes your code messy and hard to maintain.
The try-catch block lets you wrap risky code in a safe container. If something goes wrong, the program jumps to the catch part where you can handle the error gracefully, like showing a friendly message or trying a backup plan.
if (file_exists) { read_file(); } else { print("Error: file missing"); }
try { read_file(); } catch (const std::exception& e) { print("Error: file missing"); }
It enables your program to keep running smoothly even when unexpected problems happen, improving user experience and program reliability.
Think of an online shopping app that tries to process payment. If the payment server is down, a try-catch block can catch that error and show a message like "Payment failed, please try again later" instead of crashing.
Try-catch blocks help handle errors without crashing the program.
They keep your code clean by separating normal logic from error handling.
They improve user experience by managing unexpected problems smoothly.
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
