参考程序代码:
#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 num1, num2;
cout << "Enter two numbers: ";
cin >> num1 >> num2;
try {
double result = divide(num1, num2);
cout << "Result: " << result << endl;
} catch (const char* e) { // 捕获字符串类型的异常
cout << "Error: " << e << endl;
}
return 0;
}