Program to implement exception handling with the functionality of testing throw restrictions.
#include <iostream.h>
#include<conio.h>
void divide(int a, int b) {
if (b == 0) {
throw "Division by zero error!";
} else {
cout << "Result: " << a / b << endl;
}
}
int main() {
int x, y;
cout << "Enter two numbers: ";
cin >> x >> y;
try {
divide(x, y);
} catch (const char* msg) {
cerr << "Exception caught: " << msg << endl;
}
getch();
return 0;
}
Program to implement exception handling without the functionality of testing throw restrictions.
#include <iostream.h>
#include<conio.h>
int divide(int a, int b) {
if (b == 0) {
return -1; // Error code for division by zero
}
return a / b;
}
int main() {
cout<< "Enter a Divident: ";
int divident;
cin >> divident;
cout<< "Enter a divisor: ";
int divisor;
cin >> divisor;
int result = divide(divident, divisor);
if (result == -1) {
cout << "Error: Division by zero!" << endl;
} else {
cout << "Result: " << result << endl;
}
getch();
return 0;
}