通过自定义异常类与宏结合实现结构化异常输出,包含文件、行号等信息,并利用fmt库或ostringstream进行格式化,结合全局捕获确保统一输出格式,提升调试效率与日志可读性。

在C++中,异常信息的格式化输出可以通过结合标准异常类与字符串处理机制来实现。核心思路是捕获异常后,将异常信息按需组织成结构化或可读性强的格式输出,比如包含时间、异常类型、错误消息、文件位置等。
通过继承std::exception或其派生类(如std::runtime_error),可以封装格式化的错误信息。
示例:
#include <stdexcept>
#include <string>
#include <iostream>
#include <sstream>
class FormattedException : public std::runtime_error {
public:
template<typename... Args>
FormattedException(const std::string& file, int line, const std::string& msg, Args... args)
: std::runtime_error(formatMessage(file, line, msg, args...)) {}
private:
template<typename... Args>
static std::string formatMessage(const std::string& file, int line, const std::string& msg, Args... args) {
std::ostringstream oss;
oss << "[" << file << ":" << line << "] Error: " << msg;
// 这里可以扩展参数格式化逻辑
return oss.str();
}
};
// 辅助宏,自动注入文件和行号
#define THROW_FORMATTED(msg) \
throw FormattedException(__FILE__, __LINE__, msg)
使用宏可以自动记录抛出异常的位置,提升调试效率。
立即学习“C++免费学习笔记(深入)”;
用法示例:
try {
if (some_error) {
THROW_FORMATTED("Failed to open file 'config.txt'");
}
} catch (const std::exception& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
输出可能为:
[main.cpp:42] Error: Failed to open file 'config.txt'
若项目中使用了fmt库(如{fmt}或std::format in C++20),可实现更灵活的格式控制。
示例(需包含fmt):
#include <fmt/format.h>
#include <stdexcept>
#include <string>
#define THROW_FMT(file, line, fmt_str, ...) \
throw std::runtime_error(fmt::format("[{}:{}] {}", file, line, fmt::format(fmt_str, __VA_ARGS__)))
// 使用
// THROW_FMT(__FILE__, __LINE__, "Unable to connect to {} on port {}", host, port);
在main函数中捕获所有异常,确保格式化输出一致。
int main() {
try {
// 业务逻辑
} catch (const std::exception& e) {
std::cerr << "[EXCEPTION] " << e.what() << std::endl;
} catch (...) {
std::cerr << "[UNKNOWN EXCEPTION]" << std::endl;
}
return 0;
}
基本上就这些。通过自定义异常类、宏和格式化工具,能有效实现清晰、可追踪的异常信息输出。关键在于统一抛出方式和捕获处理,便于日志记录和调试。
以上就是C++如何实现异常信息格式化输出的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号