请修改倒数第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 14:42:32 浏览: 54
修改后的代码如下:
```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`。
相关问题
#include<iostream>#include<exception>using namespace std;class A{};int func1 (int m,int n){ try{ if(n==0) throw A(); cout <<"in funcl" <<endl; return m/n; } catch(exception){ cout <<"catched in funcl"<<endl; } cout << "before end of funcl"<<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;}写出输出结果
当运行这段代码时,输出结果如下:
```
catched in funcl
before end of funcl
catched in main
end of main
```
解释一下这个输出结果:
1. 首先,我们调用`func1(5,0)`,由于`n`等于0,所以会抛出一个`A`类型的异常。
2. 异常被捕获后,`func1`函数输出字符串"catched in funcl",然后执行语句`cout << "before end of funcl" << endl;`,输出字符串"before end of funcl",最后返回`m/n`的结果。
3. 控制权回到`main`函数中,捕获到了`A`类型的异常,输出字符串"catched in main"。
4. 执行语句`cout << "end of main" << endl;`,输出字符串"end of main"。
5. 程序正常结束,返回0。
#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; } 输出程序
程序输出:
```
catched in main
end of main
```
解释:在 `func1` 函数中,如果除数 `n` 为零,则会抛出 `A` 类型的异常。在 `main` 函数中,我们使用 `catch` 语句捕获了 `A` 类型的异常,并输出了相应的提示信息。
由于在 `func1` 函数中已经捕获了异常,所以程序不会继续执行 `before end of func1` 和 `return m / n` 语句,而是直接跳转到 `catch` 语句块。由于在 `main` 函数中使用了 `catch (A &) `,所以会捕获到 `A` 类型的异常,并输出相应的提示信息。最终输出 `end of main`。
阅读全文