在catch块内运行时检测

bbo*_*234 7 c# catch-block

如何检测何时从catch块中调用当前正在执行的代码?

void SomeFunction()
{
    // how do I detect whether I am being called from within a catch block?
}
Run Code Online (Sandbox Code Playgroud)

编辑:

对于那些要求,我想实现这样的类,不要错过错误冒泡逻辑:在编写此代码示例时,我收到编译器错误"在catch子句之外不允许使用不带参数的throw语句"所以无论如何,这有点摧毁了我的想法.

public class ErrorManager {

    public void OnException(Exception ex) {
        LogException(ex);
        if (IsInsideCatchBlockAlready()) {
            // don't destroy the stack trace, 
            // but do make sure the error gets bubbled up
            // through the hierarchy of components
            throw; 
        } else {
            // throw the error to make it bubble up 
            // through the hierarchy of components
            throw ex; 
        }
    }

    void LogException(Exception ex) {
        // Log the exception
    }

    bool IsInsideCatchBlockAlready() {
        // How do I implement this?
    }
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 3

你不知道。没有办法知道如果抛出异常,它是否会被捕获或使程序崩溃。您可以使用代码分析工具在编译时进行猜测,但在代码运行时这不是一个选项。