#include <iostream>
#include <exception>
// 定义一个自定义异常类
class MyException : public std::exception {
public:
const char* what() const throw () {
return "My custom exception occurred";
}
};
void mayThrow() {
// 可能抛出异常的函数
bool error = true;
if (error) {
throw MyException();
}
}
int main() {
try {
mayThrow();
} catch (const MyException& e) {
// 捕获自定义异常
std::cout << "Caught an exception: " << e.what() << '\n';
} catch (const std::exception& e) {
// 捕获标准库异常
std::cout << "Caught a standard exception: " << e.what() << '\n';
} catch (...) {
// 捕获所有其他类型的异常
std::cout << "Caught some other exception\n";
}
return 0;
}
std::exception 的自定义异常类 MyException,并重写了 what() 方法来返回异常信息。mayThrow() 函数中根据条件抛出了一个 MyException 异常。main() 函数中,使用 try 块包裹可能抛出异常的代码,并使用多个 catch 块来捕获不同类型的异常:catch 块专门捕获 MyException 类型的异常。catch 块捕获所有标准库异常(如 std::runtime_error)。catch (...) 捕获所有未被前两个 catch 块捕获的异常。上一篇:c++ 计时器
下一篇:c++ +=
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站