3

I am using the YAX Serializer (current NuGet version). When I run this code:

void Main()
{
    try
    {
        int zero = 0;
        int result = 100 / zero;
    }
    catch (DivideByZeroException ex)
    {
        LogSaveException(ex);
    }
}

public void LogSaveException(object value)
{
    try
    {
        YAXSerializer serializer = new YAXSerializer(value.GetType());
        string loggedString = serializer.Serialize(value);
        Console.WriteLine(loggedString);
    }
    catch (StackOverflowException)
    {
        Console.WriteLine("Log Error", "Could Not Log object of type " 
                  + value.GetType().ToString() +" due to stack overflow.");
    }
    catch (Exception)
    {
        Console.WriteLine("Log Error", "Could Not Log object of type " 
                + value.GetType().ToString());
    }
}

The app ends on this line: string loggedString = serializer.Serialize(value);

I have tried to catch any exception that I can see would happen. But the app just ends.

I tried running it in LinqPad and it crashed LinqPad. I tried to debug the crash of LinqPad (even though I do not have the source, sometimes you can get some info from it.) When I did that it said that there was a StackOverflowException. But my catch statement did not catch it.

What would cause a total death like that? How how do I guard against it?

Vaccano
  • 78,325
  • 149
  • 468
  • 850

2 Answers2

6

Stackoverflow exceptions have limited "catchability" in CLR > 2.0. See the blog post below for more details; the behavior you're experiencing is exactly what's described.

See: http://blogs.msdn.com/b/jaredpar/archive/2008/10/22/when-can-you-catch-a-stackoverflowexception.aspx

While annoying, this does make sense: if you've blown your stack, what would a consistent/safe/sane recovery look like?

Will Chesterfield
  • 1,780
  • 12
  • 15
2

Seems like a serious error with the YAXSerializer.

StackOverflowException cannot be caught (see here amongst others for reference) because there's rarely any recovery from such a serious error.

EDIT: or it's an error with the class you're serializing. Do you have a cyclic reference in the object you're passing in?

Community
  • 1
  • 1
Dan Puzey
  • 33,626
  • 4
  • 73
  • 96