Prevent debugger from stopping on an Exception in a Compiled LambdaExpression - c#

In my program, I create dynamic lambda expressions and then compile them to delegates. These delegates are then invoked to extract information from my entities.
Some of the delegates may throw exceptions, I've caught the exception where I call the delegate. I've enabled "Enable just my code" and applied [DebuggerNonUserCode] attribute to where the LambdaExpression is created, where compiled, and where Called. But because in Debug>Exceptions>Common Language Runtime Exceptions, the Thrown check box is checked, visual studio always stops on the error, which is a major inconvenience for the developers.
It seems that [DebuggerNonUserCode] should somehow be applied to the compiled delegate, but how? Or any other suggestion?
Thanks.

As far as I know, you cannot apply attributes to anonymous methods generated using expressions, aside from possibly some horrible messing around with dynamic type generation.
However, a possible suggestion would be to go to the exception menu in Debug > Exceptions and choose which exceptions you want to break on specifically. If your expressions tend to throw exceptions of specific kinds, you can just disable breaking on those exceptions.

Related

Debugger shows properties that throw an exception

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:
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?
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".

How to detect Visual Studio debug execution context from within code?

I'm looking for a way to detect how code is called during a debugging session in Visual Studio. Trying to differentiate these two contexts:
Ordinary debugging, whether running or single stepping.
Called via the debugger itself, such as my ToString being called from the watch window.
(I'm doing this because I have some non-release thread validation code I want to disable in the second case.)
Anyone have a way to do this, or ideas about things to pursue? I'm fine with hacky, tricksy methods, even if they are specific to a particular version of VS.
Things that don't work:
Grabbing a StackTrace and looking for something magic that means the debugger is calling in, rather than regular code. VS uses the current thread in its current state to call out of for the Watch window, so all the StackTrace is going to see is the current stack at the debugger breakpoint + the getter/ToString that the Watch window is calling, right on top of it.
This situation typically arises when methods that Visual Studio assumes are pure (i.e. evaluation has no impact on the state of the program) either have side effects or have preconditions that the debugger violates.
These situations are best solved using the following tools:
DebuggerBrowsableAttribute: Apply this attribute to properties:
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
Apply to all properties whose get method is not pure, i.e. the getter alters the state of the program, either through setting a cached value or otherwise
Apply to all properties whose get method has preconditions the debugger could violate, such as threading restrictions, cross-thread invocations (don't forget implicit if you use COM interop)
DebuggerDisplayAttribute: Apply this attribute to all types whose ToString() implementation performs non-trivial operations (avoid debugger performance impact) or has preconditions the debugger might not meet (e.g. threading requirements). This attribute is used instead of calling ToString() for these types.
DebuggerTypeProxyAttribute: Apply this attribute to types that require special consideration for when, what, and how information is presented in the debugger. The .NET framework itself uses this attribute extensively to provide features like clear output for the List<T> and HashMap<T> types, and even to improve information available for types like Lazy<T> that are sometimes OK to evaluate and other times could affect the state of the program.
As far as ordinary debugging goes, I think this is what you want:
System.Diagnostics.Debugger.IsAttached
Here's the documentation.
This won't help with the watch window though. On this, maybe the StackTrace class can help but I haven't tried it myself. It's in the same namespace.

Source of System.NullReferenceException

I am implementing a error logger for a web shop and just logging a NullReferenceException in a specific class is only useful to a certain level. I am not really interested in how to prevent the exception, as I am aware of that, but sometimes it still happens thus the error logger.
Then the question is: How do I find the source of a System.NullReferenceException inside all the exception information.
Make sure you log the full stack trace. Assuming you've got debug information turned on (no reason not to for a web app...) you should be able to get to the line which caused the problem.
Of course, that won't always give you all the information you need, if you've got:
if (foo.Bar.Baz && person.Address.Road.Length)
in a single line... but it's the best starting point you'll get.
Additionally, adding argument validation to methods can make it a lot simpler to pin down what's wrong. Personally I'm a fan of helper methods for this. For example, in Noda Time we have Preconditions, so I can just call:
Preconditions.CheckNotNull(foo, "foo");
(which also returns the value of foo, which is handy in constructors which are copying arguments into fields).
The earlier you can detect the unexpectedly-null reference, the better.
If I understand the question correctly, in Visual Studio, go to Debug > Exceptions, and check all options to throw exceptions. This will allow you to see everything that is being thrown while debugging. You can possibly use the contents of InnerException to determine what the root location of the error is being caused.

C#: Any way to suppress compiler errors similar to suppressing warning messages?

I have the following code that generates a compiler error:
Boolean IConvertible.ToBoolean(IFormatProvider provider)
{
ThrowHelper.ThrowInvalidCast(typeof(MyType), typeof(Boolean));
}
The compiler is complaining that not all code paths return a value. The problem here is that ThrowHelper will ALWAYS throw an error. It is a static class calling a static method.
I understand that I can satisfy the compiler with a silly "return true" after the ThrowHelper call, but that seems like unnecessary code. I know I can suppress warning messages, but when I tried to use the SuppressMessageAttribute it doesn't stop the compiler from complaining. Any way to suppress this error only for this method?
You could have the method in ThrowHelper only create the exception, not actually throw it.
Boolean IConvertible.ToBoolean(IFormatProvider provider)
{
throw ThrowHelper.CreateInvalidCast(typeof(MyType), typeof(Boolean));
}
This would probably result in a better stack trace as well: it would point at ToBoolean, not at ThrowInvalidCast.
There is no way to suppress an error other than to fix it.
An error, by its nature, is indicating that the compiler believes it cannot generate valid code. The only way to suppress errors is to fix them. Just add the return statement it wants and then raise an issue on Microsoft Connect indicating that you believe the compiler is getting this one wrong.
I suspect, however, that this is expected behaviour as the compiler is not aware that the method you are calling will always throw and to determine that in a predictable manner for any possible call tree would be difficult, if not impossible (imagine if you called a chain of 20 methods before concluding with a throw).
A simple brain exercise why the requested feature could lead to problems. Imagine that ThrowHelper.ThrowInvalidCast is defined in some 3rd-party library. You might know that the method always throws and tell the compiler about it or a very advanced static analyzer might be able to determine that the method always throws at the moment the code is compiled.
Now some other developer deploys an updated version of that library. Now the method doesn't always throw. All of a sudden, there is a case that your method has no return path. Just to handle that case the compiler (or the runtime) would have to include a backup plan what to do in such a situation. Quite a lot of overhead for something that can easily be fixed by writing correct code.
UPDATE: Theoretically, C# could be extended to allow for methods with no return path. Eric Lippert mentioned that in a comment to Jon Skeet's answer here:
A "never" method would simply be a void method that is not allowed to have a reachable end point or any return statements. That solves the problem at compile time. At runtime, it's the verifier's responsibility to ensure that methods actually implement their return type semantics correctly; the verifier could similarly determine that there are no return instructions and that the end point is not reachable.

Debugging a C# Object Initializer

Does anyone have any tips for debugging exceptions in a C# object initializer block? The object initializer syntax is basically all or nothing, which can make it especially difficult to troubleshoot inside of a LINQ query. Short of breaking the object creation out to a separate method, is there anything I can do to see which property setter is throwing an exception?
Disabling the option to step over property setters [Step over properties and operators (Managed Only)] can allow you to step into the property setters.
Otherwise, the best option is often to just break it out and debug it outside of the LINQ statement. You can wrap your initialization parameters into an anonymous type in linq, and construct your object(s) outside of your linq statement for debugging purposes.
Have you set up VS to break when an exception is thrown? (the default is to break only on unhandled exceptions). Debug | Exceptions, and check "thrown".
That alone is probably not an answer to your question, but it might help with the debugging.
Beyond that, you could temporarily break your code out of the initializer block (just for debugging), and then if you want, you can reinstate the initializer block once you have the code working.
Break it out of the object initializer block where your setting each property individually. That way you can actually step into the code.

Categories