Caught exception is null itself ! Caught exception is null itself ! asp.net asp.net

Caught exception is null itself !


For anyone ending up here, I've found an instance where this is possible (If only detectable in the debugger). VS2013 Update 4.

Broken:

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

The solution is to name your exception variables differently.

Fixed:

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


In my case, the cause was a StackOverflowException. Such exceptions normally don't reach the catch block at all, but this time, for some reason I don't understand, it did reach the catch block, but the exception was null.


I just ran into an issue where someone was passing ex.InnerException to a method, where ex was the root. Since the parameter was also called ex it led to some confusion in the debugger when I looked at the originally caught exception. This was likely the result of some careless refactoring.

e.g.:

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

This was refactored as such:

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