Exception:
In C++, exceptions are a way to deal with errors and unusual conditions that may arise during a program's execution. The program looks for a handler that can properly handle and catch an exception whenever one is thrown.The throw keyword is used to throw exceptions in C++, and a try-catch block is used to catch them.
The basic syntax for throwing an exception is:
throw exception_type;
The basic syntax for catching an exception is:
try {
// code that may throw an exception
} catch (exception_type e) {
// code to handle the exception
}
Example:
#include <iostream>
using namespace std;
double divide(double a, double b) {
if (b == 0) {
throw "Division by zero error";
}
return a / b;
}
int main() {
double x = 10, y = 0;
try {
double result = divide(x, y);
cout << "Result: " << result << endl;
} catch (const char* e) {
cerr << "Exception: " << e << endl;
}
return 0;
}
Output:
Exception: Division by zero error