通过自定义异常类与宏结合实现结构化异常输出,包含文件、行号等信息,并利用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)
结合宏实现便捷抛出
使用宏可以自动记录抛出异常的位置,提升调试效率。
立即学习“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;
}
输出可能为:
本文档主要讲述的是Android传感器编程;传感器是一种物理装置或生物器官,能够探测、感受外界的信号、物理条件(如光、热、湿度)或化学组成(如烟雾),并将探知的信息传递给其它装置或器官。同时也可以说传感器是一种检测装置,能感受被测量的信息,并能将检测的感受到的信息,按一定规律变换成为电信号或其它所需形式的信息输出,以满足信息的传输、处理、存储、显示、记录和控制等要求。它是实现自动检测和自动控制的首要环节。感兴趣的朋友可以过来看看
[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;
}
基本上就这些。通过自定义异常类、宏和格式化工具,能有效实现清晰、可追踪的异常信息输出。关键在于统一抛出方式和捕获处理,便于日志记录和调试。









