如何在发生异常时运行代码

How to run code even when an exception happens

本文关键字:运行 代码 异常      更新时间:2023-10-16

我有这样的代码:

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