如何在不传递变量的情况下获取当前异常?

Pie*_*ant 10 c# exception-handling

我正在寻找一种方法来检索当前的异常,而不必将其作为变量传递.

假设以下代码

public void MakeItFail()
{
    try
    {
        throw new FailException();
    }
    catch // Yes I'm aware that this shouldn't be done, but I don't want to go through all the code base and change it
    {
        ShowMessage("An error occured");
    }
}

public void ShowMessage(string message)
{
    // How can I retrieve the exception here
}
Run Code Online (Sandbox Code Playgroud)

在监视窗口中,我可以使用$ exception来获取当前异常.是否有相同的代码?

SLa*_*aks 8

不,没有.

您需要使用参数.

  • 实际上有:`var exceptionBeingThrown = Marshal.GetExceptionPointers()!= IntPtr.Zero;` (3认同)

Cha*_*ion 7

尝试在首次加载应用程序时订阅此事件。

AppDomain.CurrentDomain.FirstChanceException += (s, e) =>
{
    ShowMessage(e.Exception.Message);
};
Run Code Online (Sandbox Code Playgroud)