请修改倒数第3行为: catch(A &){ ,修改exception,#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 20:39:52 浏览: 45
修改后的代码如下所示:
```
#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 (A &) {
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 (exception)` 修改为 `catch (A &)`。这是因为在 `func1()` 中,我们抛出的是 `A` 类型的异常,因此在异常处理代码中应该使用 `catch (A &)` 来捕获异常。同时,这里也省略了 `catch (A &a)` 中的变量名,因为在这里我们并不需要使用这个变量。
阅读全文