Proper way to find the innermost exception?

前端 未结 4 1950
孤独总比滥情好
孤独总比滥情好 2021-02-08 06:16

I\'m working with some classes which, when throwing, have a relatively deep InnerException tree. I\'d like to log and act upon the innermost exception which is the one having th

4条回答
  •  孤城傲影
    2021-02-08 06:58

    You could use the GetBaseException method. Very quick example:

    try
    {
        try
        {
            throw new ArgumentException("Innermost exception");
        }
        catch (Exception ex)
        {
            throw new Exception("Wrapper 1",ex);
        }
    }
    catch (Exception ex)
    {
        // Writes out the ArgumentException details
        Console.WriteLine(ex.GetBaseException().ToString());
    }
    

提交回复
热议问题