代码之家  ›  专栏  ›  技术社区  ›  Pierre-Alain Vigeant

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

  •  10
  • Pierre-Alain Vigeant  · 技术社区  · 15 年前

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

    假设下面的代码

    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
    }
    

    在监视窗口中,我可以使用$exception获取当前异常。是否有等效的代码?

    2 回复  |  直到 15 年前
        1
  •  8
  •   SLaks    15 年前

    不,没有。

    你需要使用一个参数。

        2
  •  3
  •   ChaosPandion    15 年前

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

    AppDomain.CurrentDomain.FirstChanceException += (s, e) =>
    {
        ShowMessage(e.Exception.Message);
    };