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

在C++中,异常信息的格式化输出可以通过结合标准异常类与字符串处理机制来实现。核心思路是捕获异常后,将异常信息按需组织成结构化或可读性强的格式输出,比如包含时间、异常类型、错误消息、文件位置等。
使用std::exception派生类自定义异常
通过继承std::exception或其派生类(如std::runtime_error),可以封装格式化的错误信息。
示例:
#include#include #include #include class FormattedException : public std::runtime_error { public: template FormattedException(const std::string& file, int line, const std::string& msg, Args... args) : std::runtime_error(formatMessage(file, line, msg, args...)) {} private: template 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)
结合宏实现便捷抛出
使用宏可以自动记录抛出异常的位置,提升调试效率。
用法示例:
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库(如{fmt}或std::format in C++20),可实现更灵活的格式控制。
示例(需包含fmt):
#include#include #include #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;
}
基本上就这些。通过自定义异常类、宏和格式化工具,能有效实现清晰、可追踪的异常信息输出。关键在于统一抛出方式和捕获处理,便于日志记录和调试。
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















