Here’s a basic example demonstrating exception handling in C++:
#include <iostream>
using namespace std;
int main() {
int dividend, divisor;
cout << "Enter dividend: ";
cin >> dividend;
cout << "Enter divisor: ";
cin >> divisor;
try {
if (divisor == 0)
throw "Division by zero error!";
cout << "Result: " << dividend / divisor << endl;
} catch (const char* msg) {
cout << "Exception: " << msg << endl;
}
return 0;
}
throw "Division by zero error!".catch block catches this exception and displays an error message, allowing the program to handle the error gracefully.catch blocks can be used to handle different types of errors specifically.