c++在 CException类的成员函数Reacon()中用cout显示异常的类型,在函数fn1()中用throw抛出异常,在主函数的try模块中调用fn1(),在catch模块中捕获异常
时间: 2024-03-10 09:49:06 浏览: 85
好的,以下是一个示例代码,实现了你所描述的功能:
```c++
#include <iostream>
#include <exception>
using namespace std;
class MyException : public exception {
public:
virtual const char* what() const throw() {
return "My Exception";
}
};
class MyDerivedException : public MyException {
public:
virtual const char* what() const throw() {
return "My Derived Exception";
}
};
class MyExceptionClass {
public:
void fn1() {
throw MyDerivedException();
}
};
int main() {
MyExceptionClass obj;
try {
obj.fn1();
}
catch (MyException& e) {
cout << "Exception caught: " << e.what() << endl;
}
return 0;
}
```
在这个例子中,我们定义了两个异常类 `MyException` 和 `MyDerivedException`。`MyDerivedException` 是从 `MyException` 派生而来的。在 `MyExceptionClass` 类中的 `fn1()` 函数中,我们抛出了一个 `MyDerivedException` 类型的异常。
在主函数中的 `try` 块中,我们调用了 `MyExceptionClass` 对象的 `fn1()` 函数,这个函数抛出了异常。在 `catch` 块中,我们捕获了异常,并使用 `e.what()` 函数来输出异常的类型。
注意:在 `catch` 块中,我们使用了 `MyException&` 类型的参数,这是因为 `MyDerivedException` 是从 `MyException` 派生而来的,所以我们可以使用 `MyException&` 来捕获这个异常。如果我们在 `catch` 块中使用了 `MyDerivedException&` 类型的参数,则会出现编译错误。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)