An exception is an unexpected event that occurs during
program execution. For example,
divide_by_zero = 5 / 0;
The above code causes an exception as it is not possible to
divide a number by 0.
The process of handling these types of errors in C++ is
known as exception handling.
C++ provides three primary keywords for handling exceptions:
1.try – Defines
a block of code that might throw an exception.
2.catch – Handles the exception thrown from the try
block.
3. throw – Used
to throw an exception.
The basic syntax for exception handling in C++ is given below:
try {
// code that may
raise an exception
throw argument;
}
catch (exception) {
// code to handle
exception
}
#include <iostream>
using namespace std;
int main() {
int numerator, denominator;
cout << "Enter numerator: ";
cin >> numerator;
cout << "Enter denominator: ";
cin >> denominator;
try {
if (denominator == 0) {
throw "Division by zero is not allowed!";
}
cout << "Result: " << (numerator / denominator) << endl;
}
catch (const char* errorMessage) {
cout << "Error: " << errorMessage << endl;
}
cout << "Program continues normally..." << endl;
return 0;
}