定义一个异常类CException,有成员函数getMessage(),用来显示异常的信息。定义一个函数fun1()触发异常,在main函数try模块调用fun1(),在catch模块中捕获该异常,观察程序的执行流程
时间: 2023-06-16 16:07:32 浏览: 52
下面是C++的代码实现:
```cpp
#include <iostream>
#include <string>
using namespace std;
class CException {
private:
string message;
public:
CException(const string& msg) : message(msg) {}
string getMessage() const {
return message;
}
};
void fun1() {
throw CException("This is an exception!");
}
int main() {
try {
fun1();
}
catch (CException& e) {
cout << "Exception caught: " << e.getMessage() << endl;
}
return 0;
}
```
程序的执行流程如下:
1. 在main函数中调用fun1(),fun1()抛出一个CException类型的异常。
2. 由于在fun1()中没有处理该异常,所以该异常被抛到了上一级的调用栈中,即main函数。
3. 在main函数中,try模块试图执行fun1(),但是fun1()抛出了一个异常,所以程序跳转到catch模块。
4. 在catch模块中,我们捕获了该异常,并且调用了getMessage()函数来获取异常的信息。
5. 最终,程序正常结束。