2

I can't find an answer to this. Hope anyone can help.

I have a property setter that throws an exception if the value doesn't meet certain conditions. The class where the property lives is serialized/deserialized.

When deserializing the class in .NET 2.0 the exception is caught. If I change the project target to .NET 4.0 the exception is not caught!

Any Idea?

Thanks, Sam


Sorry. By 'exception' I'm referring to one that I throw. Here's a sample code.

This is a sample class that I want serialized/deserialized:

public class MyClass
{
    public string Name
    {
        get{return myName;}
        set
        {
            if (value == "") throw new Exception("Name is blank!");
            myName = value;
        }
    }

    private string myName;
}

And here's the code that calls the deserializer.

        try
        {
            XmlSerializer xs = new XmlSerializer(typeof(MyClass));
            using (FileStream stream = File.OpenRead("myclass.xml"))
            {
                MyClass mc = xs.Deserialize(stream) as MyClass;
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

Here's the "myclass.xml" file to test the exception.

<?xml version="1.0"?>
<MyClass>
  <Name></Name>
</MyClass>

Using .NET 2.0 I get the message box with the exception message. Using .NET 4.0 I get "Exception unhandled by user code".

Thanks,

Sam

Sam
  • 21
  • 2
  • 1
    What do you mean by "the exception is caught"? Can you provide some code and an explanation of which exception is thrown/not thrown or caught/not caught? – Martin Liversage May 25 '11 at 08:22
  • Could you post a narrowed down sample code allowing to reproduce/illustrate the issue? – Darin Dimitrov May 25 '11 at 08:29
  • Confirmed - I tested with 3.5 (Exception shown correctly to user), and 4.0 (Exception unhandled by user code). – RB. May 25 '11 at 11:39
  • If you run the program outside the IDE, you will find that the exception is handled in all cases. Similarly, if you disable "Break on user-unhandled CLR exceptions", the exception will be handled. I don't understand why there is this change in behaviour though. – RB. May 25 '11 at 11:42
  • Interesting! I didn't test outside the IDE. – Sam May 25 '11 at 11:55
  • What could be the problem?? Running the program outside the IDE while developing it is just not feasible. – Sam May 25 '11 at 11:57

1 Answers1

0

A temporary workaround is to disable breaking on user-unhandled exceptions.

  • Debug
    • Exceptions...
      • Untick "User-unhandled" for "Common Language Runtime Exceptions".

Disable exception handling

You can disable this for the specific exception you are throwing if you need granularity.

Note that this should only be considered a temporary workaround. You will generally want to have this ticked, as it's a really useful debugging aid!

RB.
  • 36,301
  • 12
  • 91
  • 131