Question

So, I have a list of objects, in this case, ExceptionInfo. These objects contain information to be put into an Exception object. However, the Exceptions are nested and the only way to assign the InnerException property of an Exception object is to specify it at construction.

So, I hvae something like so:

    static Exception ListToNestedExceptions(List<ExceptionInfo> l, int index=0)
    {
        if (index > l.Count)
        {
            return null;
        }
        var e = new Exception("", ListToNestedExceptions(l, ++index));
        e.Data[ExceptionDataKeys.StackTrace] = l[index].Stacktrace;
        return e;
    }

I know that in theory it is possible to do everything with iteration that is possible with recursion, however, I can't see how that would apply here. I'm fine with this version, but out of curiosity, is it possible to turn this into an interative version? Also, would this even be possible to apply tail call optimizations to?

Was it helpful?

Solution

Try the following sample without recursion. The main idea is to iterate from the last ExceptionInfo in the list down to the first.

public class ExceptionInfo
{
    public string Message;
}

public static Exception MakeException(List<ExceptionInfo> list)
{
    if (list == null || list.Count == 0)
        throw new ArgumentNullException("list");

    Exception ex = new ApplicationException(list.Last().Message);
    if (list.Count >= 2)
        for (int i = list.Count - 2; i >= 0; i--)
            ex = new Exception(list[i].Message, ex);
    return ex;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top