计算两数相除并输出结果。使用两个 catch 子向,分别捕捉除数为。的异常和参数输入有误异常。编译并运行,当输入除数为。时,将有异常出现,当输入的不是整数时,如将30输成了 30,出现的是另一种异常
时间: 2024-05-09 16:15:26 浏览: 77
计算输入两个数的最大公约数-c++基础教程
以下是使用两个catch子句分别捕获除数为0的异常和参数输入有误异常的示例代码:
```cpp
#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
int dividend, divisor, result;
try {
cout << "Enter dividend: ";
cin >> dividend;
cout << "Enter divisor: ";
cin >> divisor;
if (divisor == 0) {
throw runtime_error("Divide by zero exception!");
}
result = dividend / divisor;
cout << "The result is: " << result << endl;
} catch (runtime_error& e) {
cout << "Error: " << e.what() << endl;
} catch (...) {
cout << "Error: Invalid input parameter!" << endl;
}
return 0;
}
```
运行示例:
```
Enter dividend: 30
Enter divisor: 0
Error: Divide by zero exception!
```
```
Enter dividend: 30
Enter divisor: 5.5
Error: Invalid input parameter!
```
阅读全文