即使发生异常,如何运行代码

时间:2014-01-08 10:33:01

标签: c++ c#-4.0 exception-handling try-catch

我有这样的代码:

try
{
   do_some_processing();
   // Write Log to appropriate place.
}
catch
{
 // add debug info to log
 // Write Log to appropriate place.
  processException();
}

正如您所看到的,我需要在有异常时和没有异常时写日志。

我有什么方法可以在一个地方做吗?而不是两次复制?

据我所知,最终在处理异常后调用,而不是在它之前调用。我是对的吗?

3 个答案:

答案 0 :(得分:4)

我会使用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;
}

答案 1 :(得分:3)

只需将其移出try-catch区块:

try
{
    do_some_processing();
}
catch
{
    // add debug info to log
    processException();
}

// Write Log to appropriate place.

答案 2 :(得分:1)

怎么样:

try{
  do_some_processing();
}catch{
  // add debug info to log
  processException();
}

// write log to appropriate place
相关问题