2

I have the following:

    private int order;
    public int Order {
        get { return order; }
        set {
            if ((value < 0) || (value > 99)) {
                throw new Exception(string.Format("{0} must be between 0 and 99", value.ToString()));
            } else {
                order = value;
            }
        }
    }

This is called here:

            try {
                property.SetValue(reference, convertedValue, null);
            } catch (Exception e) {
                var a = e;
            }

When I set a value of 50 everything works okay. When I set the value to 123 and step through with the debug it goes to the property.SetValue line and then next thing is it gives me this and points to the end of the "} else {" code block in the first code snippet.

System.Exception was unhandled by user code
  HResult=-2146233088
  Message=123 must be between 0 and 99
  Source=Test.Storage
  StackTrace:
       at Storage.Models.Reference.set_Order(Int32 value) in C:\Code K\139- Aug  23\Common\Storage\Models\Reference.cs:line 22
  InnerException: 

Can someone explain why the exception is not handled? I can't understand why it would not be caught with the try loop that surrounds property.SetValue. I have a debug point on var a = e; but it doesn't go there.

  • 2
    It sounds like you're breaking as soon as the exception is thrown. If you continue in the debugger you should hit your breakpoint: http://msdn.microsoft.com/en-us/library/d14azbfh.aspx – Lee Aug 25 '12 at 09:49
  • Yes I do hit the var a = e if I continue. But why is it stopping and saying the exception is not handled. That my problem. –  Aug 25 '12 at 09:56
  • @Anne - Because you've set the debugger to break as soon as the exception is thrown, and before any handlers are invoked. If you don't want it to do that, you should change the setting. – Lee Aug 25 '12 at 09:59
  • possible duplicate of [Why does my implementation of get / set give a stack error?](http://stackoverflow.com/questions/12120549/why-does-my-implementation-of-get-set-give-a-stack-error) – L.B Aug 25 '12 at 10:13

1 Answers1

4

The problem lies with the Visual Studio Debugger which, by default, enables the "Enable Just My Code" option. In your situation you are not handling your code, but the reflection code is kicking in.

If you were to run the application directly from Windows Explorer you will see that there's nothing wrong and the exception is correctly handled.

More information can be found at http://msdn.microsoft.com/en-us/library/038tzxdw%28v=vs.100%29.aspx and a similar post with a more detailed answer can be found at https://stackoverflow.com/a/2831236/146205.

Community
  • 1
  • 1
Jensen
  • 3,498
  • 2
  • 26
  • 43