Exception handling in C++ is a mechanism that allows a program to deal with runtime errors (exceptions) in a structured and controlled manner, preventing abrupt termination. It separates the normal flow of program execution from error-handling code.
The core of C++ exception handling relies on three keywords:
-
try: Atryblock encloses the code segment where an exception might occur.throw: Thethrowstatement is used to explicitly signal or “raise” an exception when a problem is detected within thetryblock. The operand ofthrowdetermines the type of the exception.catch: Acatchblock immediately follows thetryblock. It is an exception handler that “catches” an exception thrown by thethrowstatement and contains the code to handle the error. Acatchblock specifies the type of exception it can handle- Example 1: Division by Zero
#include
using namespace std;
int main() {
int a, b;
cout << “Enter two numbers: “; cin >> a >> b;
try {
if (b == 0)
throw “Division by zero error!”;
cout << “Result: ” << a / b << endl;
}
catch (const char* msg) {
cout << “Exception caught: ” << msg << endl;
}
cout << “Program continues…” << endl;
return 0;
}
OutPut
Enter two numbers: 10 0
Exception caught: Division by zero error!
Program continues…
Example 2: Using std::exception
#include
#include
using namespace std;
int main() {
try {
throw runtime_error(“Something went wrong!”);
}
catch (const exception& e) {
cout << “Caught exception: ” << e.what() << endl;
}
return 0;
}
Example 3: Multiple Catch Blocks
You can handle different exception types separately.
try {
throw 10;
}
catch (int e) {
cout << "Caught integer exception: " << e << endl;
}
catch (...) {
cout << "Caught unknown exception!" << endl;
}



