Caught exception is null itself !

后端 未结 5 1195

I have an ASP.NET applications. Everything was fine, but recently I get exceptions that are null themselves:

try
{
    // do something
}
catch (Exception ex)         


        
5条回答
  •  醉酒成梦
    2020-12-10 11:02

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

提交回复
热议问题