如何在发生异常时运行代码
How to run code even when an exception happens
我有这样的代码:
try
{
do_some_processing();
// Write Log to appropriate place.
}
catch
{
// add debug info to log
// Write Log to appropriate place.
processException();
}
如您所见,我需要在有异常和没有异常时写入日志。
有什么办法可以在一个地方做吗? 而不是复制两次?
据我所知,finally 是在异常处理之后而不是在异常之前调用的。我说的对吗?
我会使用 RAII 习语
class RaiiLogger {
public:
RaiiLogger() : exception_fired_(true) {}
void set_success() {
exception_fired_ = false;
}
~RaiiLogger() {
if (exception_fired_) {
// log it
} else {
// log it
}
}
private:
bool exception_fired_;
};
void do_work() {
RaiiLogger logger;
try {
// do some work
logger.set_success();
} catch(...) {
// handle exception
}
}
int main() {
// your code goes here
do_work();
return 0;
}
只需将其移动到try-catch
块之外:
try
{
do_some_processing();
}
catch
{
// add debug info to log
processException();
}
// Write Log to appropriate place.
怎么样:
try{
do_some_processing();
}catch{
// add debug info to log
processException();
}
// write log to appropriate place
相关文章:
- 如何在linux终端中同时编译和运行c++代码
- 尝试用java代码编译和运行c++代码
- 不同/较旧的处理器运行c++代码的方式是否不同
- 无法在 geany 上运行代码。无法执行构建命令
- 运行代码时,c++ 会终止进程
- 编译多个C++文件.调用二进制文件以运行代码
- 分段故障 运行C++代码时出现 SIGSEGV
- 如何分析在 Windows 上运行C++代码?
- 编译器资源管理器(godbolt)如何安全地运行代码?
- 如何在 vim (windows) 中编译和运行 c++ 代码
- 无法在 Visual Studio 代码中生成和运行 C++ 代码
- 连续运行C++代码和 Python 代码
- 在静态初始化期间运行代码
- C++ .我正在尝试通过使用开关内的数组来获取用户输入,但是当我运行代码时,它显示分段错误?
- 我最近更改了编译器路径以运行 c++ 代码,但现在我无法运行任何 python 代码。我该如何解决这个问题?
- 如何在Visual Studio Code的终端内运行C++代码?
- 在注入的 Dll 的 DllMain 中运行代码导致注入超时
- 并行和顺序运行代码时会产生不同的结果
- 运行代码时C++错误
- 在 CortexM0 中从 RAM 运行代码时出现硬故障