c++头歌编写异常处理的类
时间: 2023-06-20 15:10:17 浏览: 101
C++中可以使用`try-catch`语句来捕获和处理异常,同时也可以自定义异常类来实现更细致的异常处理。以下是一个简单的自定义异常类的示例代码:
```c++
#include <iostream>
#include <exception>
class MyException : public std::exception
{
public:
MyException(const char* message) : msg(message) {}
const char* what() const noexcept override { return msg.c_str(); }
private:
std::string msg;
};
int main()
{
try {
int x = 10, y = 0;
if (y == 0)
throw MyException("Divisor cannot be zero!");
std::cout << x/y << std::endl;
}
catch (const std::exception& e) {
std::cout << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
```
在上述代码中,我们定义了一个名为`MyException`的自定义异常类,它继承自标准库中的`std::exception`类,并重写了`what`方法来返回异常信息。在`main`函数中,我们使用`try-catch`语句来捕获异常并处理,在抛出异常时使用了`throw`关键字,并传递了一个`MyException`对象作为参数。在`catch`语句中,我们使用了`const std::exception&`类型的引用来捕获异常,并通过`e.what()`方法获取异常信息并输出。