Find the inner-most exception without using a while loop?

前端 未结 12 783
南旧
南旧 2020-12-12 18:54

When C# throws an exception, it can have an inner exception. What I want to do is get the inner-most exception, or in other words, the leaf exception that doesn\'t have an i

相关标签:
12条回答
  • 2020-12-12 19:25

    In fact is so simple, you could use Exception.GetBaseException()

    Try
          //Your code
    Catch ex As Exception
          MessageBox.Show(ex.GetBaseException().Message, My.Settings.MsgBoxTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
    End Try
    
    0 讨论(0)
  • 2020-12-12 19:30

    Oneliner :)

    while (e.InnerException != null) e = e.InnerException;
    

    Obviously, you can't make it any simpler.

    As said in this answer by Glenn McElhoe, it's the only reliable way.

    0 讨论(0)
  • 2020-12-12 19:31

    Not quite one line but close:

            Func<Exception, Exception> last = null;
            last = e => e.InnerException == null ? e : last(e.InnerException);
    
    0 讨论(0)
  • 2020-12-12 19:33

    If you don't know how deep the inner exceptions are nested, there is no way around a loop or recursion.

    Of course, you can define an extension method that abstracts this away:

    public static class ExceptionExtensions
    {
        public static Exception GetInnermostException(this Exception e)
        {
            if (e == null)
            {
                throw new ArgumentNullException("e");
            }
    
            while (e.InnerException != null)
            {
                e = e.InnerException;
            }
    
            return e;
        }
    }
    
    0 讨论(0)
  • 2020-12-12 19:34

    I know this is an old post, but I'm surprised nobody suggested GetBaseException() which is a method on the Exception class:

    catch (Exception x)
    {
        var baseException = x.GetBaseException();
    }
    

    This has been around since .NET 1.1. Documentation here: http://msdn.microsoft.com/en-us/library/system.exception.getbaseexception(v=vs.71).aspx

    0 讨论(0)
  • 2020-12-12 19:35

    Another way you could do it is by calling GetBaseException() twice:

    Exception innermostException = e.GetBaseException().GetBaseException();
    

    This works because if it is an AggregateException, the first call gets you to the innermost non-AggregateException then the second call gets you to the innermost exception of that exception. If the first exception is not an AggregateException, then the second call just returns the same exception.

    0 讨论(0)
提交回复
热议问题