try, catch & throw Basics
🟡 Intermediate
📖 Definition
C++ exception handling separates normal execution code inside a try block from error handling logic in a catch handler. An exception object is emitted using the throw keyword when a runtime error condition occurs.
💡 Code Example
#include <iostream>
double divide(double a, double b) {
if (b == 0.0) throw "Division by zero!";
return a / b;
}
int main() {
try {
std::cout << divide(10.0, 0.0) << "\n";
} catch (const char* msg) {
std::cerr << "Caught Exception: " << msg << "\n";
}
return 0;
}