Home > other >  Debugger shows properties that throw an exception
Debugger shows properties that throw an exception

Time:03-15

When using libraries (currently the PNP Core SDK) I often notice that while inspecting some objects, they have many properties that "threw an exception".
This looks like that:

enter image description here

But what does this mean exactly?

Does it mean that the value would throw an exception if I tried to access it? But I thought getters should never throw exceptions. Is this a bad practice?
So did the debugger already try to access all those properties and therefore "knows" in advance that it would throw an exception if I tried to access those properties at runtime?

What should such property states communicate to the developer? How should I behave if I see that?

CodePudding user response:

Yes, the debugger evaluates all those properties. And while doing so, he encountered an exception. The text (which is not fully visible on your screen shot) will give an indication as to why the exception was thrown. A typical cause is that the object is not valid any more (it's been disposed, for instance). Some properties might also throw an exception because they cannot be evaluated by the debugger for technical reasons. This may for instance happen when looking at instances of System.Type with the debugger.

For this very reason, it is advised that properties are lightweight and should not throw exceptions. Complex operations that involve e.g. accessing a database or querying some piece of hardware information should not be done trough properties. But not all APIs actually adhere to this recommendation.

There are even cases when the debugger may cause side effects due to its property evaluation, therefore a get property should never change the state of an object. Code that would use the following property would work differently when being debugged as when not:

public int NextNumber
{
   get
   {
       return _number  ;
   }
}

To disable property evaluation in the debugger, go to Tools->Options->Debugging and deselect "Allow property evaluation and other implicit function calls".

  • Related