捕获exception本身为null!

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

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

有时ex本身就是null

任何的想法?

对于在这里结束的任何人,我找到了一个可能的实例(如果只能在调试器中检测到)。 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); } 

解决方案是以不同方式命名您的exception变量。

固定:

 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); } 

这不可能发生。

如果你throw null ,你将从throw null得到一个NullReferenceException ; catch块中的exception永远不能为null

你有别的东西是null

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

我刚遇到一个问题,有人将ex.InnerException传递给一个方法,其中ex是根。 由于参数也被称为ex ,当我查看最初捕获的exception时,它导致调试器中的一些混乱。 这可能是一些粗心重构的结果。

例如:

 public void MyMethod(string input) { try { Process(input); } catch (Exception ex) { // <- (2) Attempting to view ex here would show null _logger.log(ex); LogInner(ex.InnerException); } } private void LogInner(Exception ex) { _logger.log(ex); // <- (1) NullReferenceExeption thrown here if(ex.InnerException != null) LogInner(ex.InnerException); } 

这被重构为:

 public void MyMethod(string input) { try { Process(input); } catch (Exception ex) { LogExceptionTree(ex); } } private void LogExceptionTree(Exception exception) { _logger.log(exception); if(exception.InnerException != null) LogExceptionTree(exception.InnerException); } 

我遇到了同样的问题,原因是:exception是一个NullReferenceException,所以你不能使用ex.Message,你应该尝试流动:

 try { // do something } catch (NullReferenceException) { Logger.Log("Error while tried to do something. Error: Null reference"); } catch (Exception ex) { Logger.Log("Error while tried to do something. Error: " + ex.Message); }