Explain use of try, catch and throw blocks in exception handling in c++
In : IMCA Subject : Object Oriented Programming C++In C++, exception handling is used to handle runtime errors so that the program can continue running or terminate gracefully. The three keywords used are:
try: This block contains code that might cause an error .throw: Used inside thetryblock to throw an exception when an error occurs.catch: This block catches and handles the exception thrown bythrow.
Example :
#include
using namespace std;
int main() {
try {
int age;
cout << "Enter your age: ";
cin >> age;
if (age < 0) {
throw age; // Throw an exception if age is negative
}
cout << "You are " << age << " years old." << endl;
}
catch (int e) {
cout << "Error: Age cannot be negative (" << e << ")" << endl;
}
return 0;
}