请修改倒数第3行为: catch(A &){,原程序如下:#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; } catch (A &) { cout << "end of main" << endl; } return 0; }
时间: 2024-03-18 14:39:48 浏览: 67
修改后的代码如下所示:
```
#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;
}
catch (A &) {
cout << "end of main" << endl;
}
return 0;
}
```
在修改后的代码中,将 `catch (A &)` 修改为 `catch (A &a)`。这是因为在 `catch (A &)` 后面没有指定变量名,而在 `catch (A &a)` 中,我们指定了变量名为 `a`。这样做的好处是,在 `catch (A &a)` 的代码中,我们可以使用变量 `a` 来处理捕获到的异常,而不需要使用默认的匿名变量。
阅读全文