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.
#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;
}catch (CustomError e) physically copies the entire object in RAM. You should ALWAYS write catch (const CustomError& e) to catch it by Reference, saving memory and preventing 'Object Slicing' issues.Can you have multiple 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.
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;
}Test your understanding of Try/Catch with these quick questions.
Question 1
What happens to the remaining code inside a `try` block immediately after an exception is thrown?
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.
#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;
}catch (CustomError e) physically copies the entire object in RAM. You should ALWAYS write catch (const CustomError& e) to catch it by Reference, saving memory and preventing 'Object Slicing' issues.Can you have multiple 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.
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;
}Test your understanding of Try/Catch with these quick questions.
Question 1
What happens to the remaining code inside a `try` block immediately after an exception is thrown?