Try/Catch
Overview
If a function throws an Exception, and it hits the main() scope uncaught, the program dies. To prevent this, we use a Try/Catch Block.
You wrap any dangerous, unpredictable code inside the try { } block. This tells the C++ runtime to 'monitor' this code. If an exception is thrown inside the try block (even if it's deeply nested 10 functions down), the execution instantly halts, abandons the try block, and teleports directly into the matching catch { } block. Here, you can safely log the error, alert the user, and allow the program to continue running normally.
Syntax
#include <iostream>
void riskyFunction(bool fail) {
if (fail) throw "Database Offline!";
std::cout << "Processing data...\n";
}
int main() {
// 1. TRY BLOCK: Monitor this code for explosions
try {
riskyFunction(true);
std::cout << "This line will NEVER print because an error was thrown above!\n";
}
// 2. CATCH BLOCK: The safety net
// It catches the specific data type thrown (a string/char pointer)
catch (const char* errorMessage) {
std::cout << "Intercepted an Error: " << errorMessage << "\n";
}
// 3. SURVIVAL
std::cout << "The program survived and is continuing normally!\n";
return 0;
}Common Pitfalls
- Catching by Value instead of Reference. If an exception throws a massive Custom Error Object, writing
catch (CustomError e)physically copies the entire object in RAM. You should ALWAYS writecatch (const CustomError& e)to catch it by Reference, saving memory and preventing 'Object Slicing' issues.
Interview Questions
catch blocks for a single try block?Yes. A try block can be followed by an infinite chain of catch blocks, each designed to catch a different data type (e.g., catch(int), catch(string), catch(NetworkError)). The compiler will mathematically evaluate them top-to-bottom and execute the first one that perfectly matches the thrown data type.
Real-World Example
Using chained Catch blocks to handle completely different types of system failures gracefully.
#include <iostream>
void parseData(int dataCode) {
if (dataCode == 1) throw 404; // Throws an int
if (dataCode == 2) throw "Corrupted Payload"; // Throws a string
}
int main() {
try {
parseData(1);
}
catch (int errorCode) {
std::cout << "HTTP Error: " << errorCode << "\n";
}
catch (const char* msg) {
std::cout << "Data Error: " << msg << "\n";
}
return 0;
}Check Your Knowledge
Test your understanding of Try/Catch with these quick questions.