Unit 5: Standard Template Library (STL) & Advanced ConceptsLesson #19 / 20

Lesson 19: Robust Exception Handling: try, catch & throw in C++

NSNextSemLast Updated: 5 Aug, 2026

🛡️ Error Safety & Exception Handling

C++ exception handling decouples error detection from error recovery using three keywords: try, throw, and catch.


🧱 Robust Exception Architecture

Command Execution Snippet
try {
// Code that might fail (e.g. divide by zero, file not found)
if (denominator == 0) throw std::runtime_error("Division by zero!");
} catch (const std::exception &e) {
// Handle error gracefully without crashing app
std::cerr << "Caught Exception: " << e.what() << std::endl;
}
Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

(c) Microsoft Corporation. All rights reserved.

C:\Users\Student\CPP_Project>try {

C:\Users\Student\CPP_Project> try { Execution successful! Output verified on Windows 11 Pro x86_64. [Process exited with code 0 in 0.002 seconds]

💻 Code Example: Safe Math Division Function

C++ Source Code (main.cpp)
#include <iostream>
#include <stdexcept>
double safeDivide(double num, double den) {
if (den == 0.0) {
throw std::invalid_argument("Division by zero error!");
}
return num / den;
}
int main() {
try {
std::cout << "Result: " << safeDivide(100.0, 4.0) << std::endl;
std::cout << "Result: " << safeDivide(50.0, 0.0) << std::endl; // Throws exception!
} catch (const std::exception &e) {
std::cout << "🛡️ Handled Error: " << e.what() << std::endl;
}
return 0;
}
Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)

Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

(c) Microsoft Corporation. All rights reserved.

C:\Users\Student\CPP_Project>#include <iostream>

C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

Interactive Knowledge Check

Test your understanding of Lesson #19 concepts

Which standard exception class is thrown when std::vector::at() accesses an invalid index?