C# How to debug Control.DoDragDrop Method - c#

I'm reading a foreign source code and there occurs sometimes a
NullException
by Drag'n'Drop operation. The problem is, that all parameters are never null, so I'd like to be able to debug this method somehow.
Any ideas ?

Any exception thrown while a drag+drop is in progress is swallowed by a catch all handler in DoDragDrop. You can see the first-chance exception in the Output window but that's all. To get the debugger to stop use Debug + Exceptions, tick the Thrown checkbox on CLR exceptions.

OK !
It seems that the Call Stack in Message Details helps to locate the problem.
Anyways.. for me it's sufficient.

Related

How to prevent break on specific exception if it's handled

Normally I want the debugger to break on ArgumentOutOfRangeException.
But within my try catch(ArgumentOutOfRangeException) that exception is already handled and so I want the debugger to not break.
I tried the DebuggerStepThrough attribute, but it still breaks.
You can do this by setting the debugger to break on user unhandled exceptions.
Go to Debug -> Exceptions, Common Language Runtime Exceptions, de-tick (uncheck) the Thrown box. Of course you can get very precise with what you want to break on by drilling down into that list. Be aware that this setting takes effect across the whole solution, you can't set it per class or method. If you do want to be more selective per method, then consider using compile directives to not include that bit of code during debug time.
As for the DebuggerStepThrough attribute, that is to prevent breaking on break points, nothing to do with breaking on exceptions.
You should check your visual studio isn't set to break on all exceptions
On the Debug menu, click Exceptions.
In the Exceptions dialog box, select Thrown for an entire category of exceptions,
for example, Common Language Runtime Exceptions.
Microsoft Visual Studio Help
There is a way. First disable debugging code that is not yours. Go to Tools > Options > Debugging > General > select "Enable Just My Code (Managed only)". Now tell the debugger that this one function is not part of your code with DebuggerNonUserCodeAttribute:
[System.Diagnostics.DebuggerNonUserCode()]
private void FunctionThatCatchesThrownException()
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException ex)
{
//...
}
}
If an exception (some other than ArgumentOutOfRangeException) gets out of the function debugger will catch it as usual, but the location of interception will be where the function is called.

Selectively ignore thrown exceptions in C# code

I have a function in C# code where a NullReferenceException is thrown periodically (expected behavior), but caught. Is there a way I can tell the Visual Studio debugger to not break on this exception for this particular section of my code?
EDIT I need to break on this exception elsewhere in my code, but not in the same function.
If I understand correctly and what you're trying to do is debug some NullReferenceException(s) but want to temporarily ignore others while debugging, you might be able to do this by marking functions that you want the debugger to ignore with the DebuggerNonUserCode attribute.
[DebuggerNonUserCode]
private void MyMethod()
{
// NullReferenceException exceptions caught in this method will
// not cause the Debugger to stop here..
}
NOTE that this will only work if the exceptions are caught in said methods. It's just that they won't cause the debugger to break if you have the debugger set to always break on NullReferenceException exceptions. And that this only works on methods, and not arbitrary sections of code inside of a method..
Assuming the exception does not bubble up to the caller, this can be achieved with DebuggerHiddenAttribute.
From the remarks
the Visual Studio 2005 debugger does not stop in a method marked with
this attribute and does not allow a breakpoint to be set in the
method.
[DebuggerHidden]
private static void M()
{
try
{
throw new NullReferenceException();
}
catch (Exception)
{
//log or do something useful so as not to swallow.
}
}
You can do this, but it does effect all exceptions in the solution.
Debug -> Exceptions -> Find... "Null Ref", de-tick Thrown.

How to fix "'System.AggregateException' occurred in mscorlib.dll"

I'm receiving an unhandled exception while debugging, and the program stops executing. The debugger doesn't show me the line so I don't know what to fix.
An unhandled exception of type 'System.AggregateException' occurred in mscorlib.dll
Additional information: A Task's exception(s) were not observed either by Waiting on the Task or accessing its Exception property. As a result, the unobserved exception was rethrown by the finalizer thread.
Cannot obtain value of local or argument '<this>' as it is not available at this instruction pointer, possibly because it has been optimized away. System.Threading.Tasks.TaskExceptionHolder
How can I troubleshoot this problem?
I also found this question which is pretty similar.
As the message says, you have a task which threw an unhandled exception.
Turn on Break on All Exceptions (Debug, Exceptions) and rerun the program.
This will show you the original exception when it was thrown in the first place.
(comment appended): In VS2015 (or above). Select Debug > Options > Debugging > General and unselect the "Enable Just My Code" option.
You could handle the exception directly so it would not crash your program (catching the AggregateException). You could also look at the Inner Exception, this will give you a more detailed explanation of what went wrong:
try {
// your code
} catch (AggregateException e) {
}
The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.
Task.Factory.StartNew(x=>
throw new Exception("I didn't account for this");
)
However, if we do this, at least the application does not crash.
Task.Factory.StartNew(x=>
try {
throw new Exception("I didn't account for this");
}
catch(Exception ex) {
//Log ex
}
)
In my case I ran on this problem while using Edge.js — all the problem was a JavaScript syntax error inside a C# Edge.js function definition.

C# rethrow an exception: how to get the exception stack in the IDE?

There has been discussion here before about the correct way to rethrow an exception. This question, instead, is about how to get useful behavior from Visual Studio when using rethrow.
Consider this code:
static void foo() {
throw new Exception("boo!");
}
static void Main(string[] args) {
try {
foo();
} catch (Exception x) {
// do some stuff
throw;
}
}
The exception that comes out has the correct stack trace, showing foo() as the source of the exception. However, the GUI Call Stack window only shows Main, whereas I was expecting it to show the exception's call stack, all the way to foo.
When there is no rethrow, I can use the GUI to very quickly navigate the call stack to see what call caused the exception and how we got there.
With the rethrow I'd like to be able to do the same thing. Instead, the call stack that the GUI shows is of no use to me. I have to copy the exception details to the clipboard, paste it to Notepad, and then manually navigate to whichever function of the call stack I'm interested in.
By the way, I get the same behavior if I add [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] or if I change the catch to just catch (Exception).
My question is: given that the code I have uses rethrow, can someone suggest a convenient way to navigate the call stack associated with the exception? I'm using Visual Studio 2010.
The debugger breaks at the throw in Main because that exception is unhandled. By default, the debugger will only break on unhandled exceptions. Once you've stopped at Main, the call stack for the original exception from foo is present in the exception, but all of the other context has been lost (e.g. locals, stack/memory state).
It sounds like you want the debugger to break on the throw in foo, so you should tell the debugger to break on first-chance exceptions:
Debug » Exceptions... (Ctrl+Alt+E)
Check "Thrown" for the exception types you care about (in this case, Commange Language Runtime Exceptions)
Click OK
Start debugging
In this case, the debugger will break immediately when foo throws an exception. Now, you can examine the stack, locals, etc., in the context of the original exception. If you continue execution (F5), the debugger will break again on the rethrow in Main.
Taking another approach, if you're running VS2010 Ultimate, you can also use IntelliTrace to "debug backwards" to see parameters, threads, and variables at the time of the exception. See this MSDN article for details. (Full disclosure: I work on a team closely related to IntelliTrace).
If you use ReSharper, you can copy exception stacktrace to clipboard, then choose in the menu: ReSharper > Tools > Browse Stack Trace (Ctrl+E,T). It will show stacktrace with clickable locations, so you'll be able to quickly navigate.
(source: jetbrains.com)
This feature is also very useful while digging through logs from users (if stacktraces of exceptions are logged).
Not that you should re-throw but here's a blog post about how to preserve the stack trace, essentially it boils down to this:
private static void PreserveStackTrace(Exception exception)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(exception, null);
}
...
catch (Exception ex)
{
// do something
// ...
PreserveStackTrace(ex);
throw;
}
Mike Stall has given a great and simple solution to your problem:
Mark the methods where you rethrow the exception with the attribute [DebuggerNonUserCode]
The IDE will consider this is not your code and will not break the debugger in such place, and instead will look further in the stack, showing the next rethrow or the initial exception place.
(if the next rethrow is also annoying, mark it as [DebuggerNonUserCode] as well, etc...)

Problem with Environment.StackTrace

On a thread that is processing new data in the system, if the data is invalid I write a message in the event log, containing the Environment.StackTrace information.
Writing in the event log throws an exception with no text message
Message:
CallStack - at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at <my method that writes in the event log>
Any ideas why this happens?
EDIT: I am interested in what can cause the Environment.StackTrace to throw exception in general, so that i can understand what is happening in my case
#anchandra I don't know if you have figured this out since, as this is now 4 years old.
However I would like to add as I just stumbled upon this myself.
So, why does Environment.StackTrace throws an exception?
First the most uninteresting answer:
As you can see in the MSDN reference to the property, it can throw an ArgumentOutOfRangeException if "The requested stack trace information is out of range.", note also that the executing context must have System.Security.Permissions.EnvironmentPermission.
Now what stumped me for a second:
It does NOT throw an exception! Yes, that is what was happening to me, it actually returned me a Stack Trace that started listing the call to Environment.StackTrace like "at System.Environment.get_StackTrace()" then it showed all the other calling methods.
Because I was logging this into an audit log, if you look at it you assume there is an exception occurring at the last frame of the stack, but that's not true, I was just happening to request a Stack Trace at that point and stick it in my error log, very dumb once I realized this.
You need to capture the stacktrace before moving onto a separate thread.
Stacktrace will only show you the frames up to the root of the thread.

Categories

Resources