捕获异常本身为null!

Xaq*_*ron 32 c# asp.net null exception

我有一个ASP.NET应用程序.一切都很好,但最近我得到了自己为null的异常:

try
{
    // do something
}
catch (Exception ex)
{
    Logger.Log("Error while tried to do something. Error: " + ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

有时exnull自己!

任何的想法?

Ben*_*ull 47

对于在这里结束的任何人,我发现了一个可能的实例(如果只能在调试器中检测到).VS2013更新4.

破碎:

try
{
    // do something
}
catch (WebException ex) // <- both variables are named 'ex'
{
    Logger.Log("Error while tried to do something. Error: " + ex.Message);
}
catch (Exception ex) // <- this 'ex' is null
{
    Logger.Log("Error while tried to do something. Error: " + ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

解决方案是以不同方式命名您的异常变量.

固定:

try
{
    // do something
}
catch (WebException webEx) // <- all good in the hood
{
    Logger.Log("Error while tried to do something. Error: " + webEx.Message); // <-
}
catch (Exception ex) // <- this 'ex' correctly contains the exception
{
    Logger.Log("Error while tried to do something. Error: " + ex.Message);
}
Run Code Online (Sandbox Code Playgroud)

  • VS2017仍然存在!我不认为他们有任何修复它的意图...... (6认同)
  • 这是正确的答案......我已经患上了它.问题仍然存在于VS2015中. (2认同)

Wil*_*sch 6

在我的例子中,原因是StackOverflowException.这样的异常通常根本不会到达catch块,但这一次,由于某些原因我不明白,它确实到达了catch块,但异常是null.