请修改倒数第3行为: catch(A &){,且修改后结果不为catched in main,#include <iostream> #include <exception> using namespace std; class A { }; int func1(int m, int n) {try { if (n == 0) throw A(); cout << "in func1" << endl; return m / n; } catch (exception) {cout << "catched in func1" << endl; } cout << "before end of func1"<< endl; return m / n; } int main() {try {func1(5, 0); cout << "in main" << endl; } catch (A &a) {cout << "catched in main" << endl; } cout << "end of main" << endl; return 0; }
时间: 2024-03-18 07:42:32 浏览: 49
babel_try_catch_loader:一个使用babel转换源文件并使用try catch子句包装所有函数(包括类方法和箭头函数)的Webpack加载程序
修改后的代码如下:
```cpp
#include <iostream>
#include <exception>
using namespace std;
class A {};
int func1(int m, int n)
{
try {
if (n == 0)
throw A();
cout << "in func1" << endl;
return m / n;
} catch (exception) {
cout << "catched in func1" << endl;
}
cout << "before end of func1"<< endl;
return m / n;
}
int main()
{
try {
func1(5, 0);
cout << "in main" << endl;
} catch (A &) {
cout << "catched in main" << endl;
}
cout << "end of main" << endl;
return 0;
}
```
修改后的代码中,将异常处理部分的 `catch (exception)` 修改为 `catch (A &)`, 这样就能捕获到 `throw A()` 抛出的异常,并输出 `catched in main`。
阅读全文