继承std::runtime_error是自定义异常的推荐做法,可复用what()实现并确保异常安全;通过std::string存储错误信息,使用noexcept保证异常抛出时不触发终止;构建继承体系如AppException派生ParseException等,便于分类捕获;抛出时按值传递、捕获时按引用接收,提升错误处理的清晰度与可控性。

在C++中自定义异常类时,继承标准库中的
std::exception
noexcept
最基础的做法是让自定义异常类 public 继承
std::exception
what()
const char*
注意:
what()7> 必须声明为 <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false;">noexcept
std::terminate
const char*
what()
std::string
c_str()
示例:
立即学习“C++免费学习笔记(深入)”;
#include <exception>
#include <string>
<p>class MyException : public std::exception {
private:
std::string msg;
public:
explicit MyException(const std::string& message) : msg(message) {}</p><pre class='brush:php;toolbar:false;'>const char* what() const noexcept override {
return msg.c_str();
}};
虽然可以直接继承
std::exception
std::runtime_error
std::logic_error
what()
std::runtime_error
std::logic_error
what()
示例:
立即学习“C++免费学习笔记(深入)”;
#include <stdexcept>
#include <string>
<p>class FileOpenException : public std::runtime_error {
public:
explicit FileOpenException(const std::string& filename)
: std::runtime_error("Cannot open file: " + filename) {}
};</p>在复杂系统中,建议设计异常类的继承体系,便于按类别捕获异常。例如定义一个根异常类,再派生出不同类型的异常。
这有助于上层代码选择性地处理特定错误,同时保留通用异常处理路径。
std::runtime_error
NetworkException
ParseException
示例:
立即学习“C++免费学习笔记(深入)”;
class AppException : public std::runtime_error {
public:
explicit AppException(const std::string& msg)
: std::runtime_error(msg) {}
};
<p>class ParseException : public AppException {
public:
ParseException(const std::string& file, int line)
: AppException("Parse error in " + file + " at line " + std::to_string(line)) {}
};</p>自定义异常类时需注意以下几点:
what()
noexcept
what()
what()
基本上就这些。继承
std::runtime_error
以上就是C++自定义异常类 继承exception最佳实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号