How to debug exceptions - c#

While logging exceptions to a database or evaluating the event viewer is very helpful. Many times we are often left wondering how to reproduce the error so we can debug it. There are some good practices that you can apply to serialize the calls and then later with some work reproduce the error and ultimately debug and fix. I am wondering what tools and or best practices are out there to efficiently debug errors to fix quickly based on collected exception information. In other words collect information about any given exception and quickly load into a debug session\step thru the code and more efficiently resolve errors.
Here is something I would consider a dream but would be extremely helpful if it existed.
try
{
//Do something that breaks
}
catch (Exception Ex)
{
LogExceptionExecution();
}
Serialize the information collected from LogExceptionExecution();
Now having the information serialized take the information completely and load directly into visual studio. Visual studio would then create a breakpoint at the start of the method and begin a debug session. The debug session would have everything loaded to recreate what caused the exception in the first place. This would allow you to debug and fix the error without spending valuable time on how to recreate the environment and load the code used during the error in order to debug and fix code.

For your case, you should write a Minidump file when exception happens. Minidumps are a mechanism for "post-mortem debugging" - debugging your application after it is "dead". A minidump is a snapshot of the memory of your application, typically taken when it is has encountered a fatal error.
As how to create a minidump in .NET, please read this.

Related

VS2013 doesn't seem to attach correctly - a debugger is attached to but not configured to debug this unhandled exception

While coding a console app, I'm using an SAP DLL.
I'm getting the following error when trying to add an SAP object:
A debugger is attached to but not configured to debug this unhandled exception. To debug this exception detach the current debugger.
Code:
SAPbobsCOM.GeneralService oGeneralService = oCmpSrv.GetGeneralService("WEPPAGE");
SAPbobsCOM.GeneralData oGeneralData = (SAPbobsCOM.GeneralData)oGeneralService.GetDataInterface(di.GeneralServiceDataInterfaces.gsGeneralData);
oGeneralData.SetProperty("U_WebId", "1");
try
{
oGeneralService.Add(oGeneralData);
}
catch (Exception e)
{
Logger.WriteLog("Error Add object " + e.Message);
}
Although the code is wrapped with try&catch, the IDE crashes.
After many searches and suggestions around the web, which did not helped, I came across this post and applied the suggested solution and enabled native code debugging under the project properties debug tab.
The result of ticking this option was that instead of letting me debug the unknown error, the exception just "disappeared" and the code runs with no interference.
Questions
Why does the exception disappears and not debugged?
Is it possible to have a different workaround for this problem since enabling the native code debugging is slowing down the app by 10x and not a real solution this problem.
Although the code is wrapped with try&catch, the IDE crashes
No, the WER dialog shows that it is your program that crashed, not the IDE. Not your code, OBServerDLL is a SAP component. And given the nature of the crash, using try/catch is not going to be able to catch this exception, it occurs on a worker thread inside the SAP code.
Do keep in mind that the crash reason is very nasty, exception code c0000005 is the equivalent of an AccessViolationException. The usual reason for it is memory corruption. Never catch an exception like that, your program cannot meaningfully continue operating.
Why does the exception disappears and not debugged?
This is certainly not supposed to happen, very unhealthy. AVEs do tend to be rather random, memory corruption does not guarantee a crash. Keep in mind that when it does occur while you are debugging then you still can't find out anything about the reason, you don't have the source code for the OBServerDLL.
enabling the native code debugging is slowing down the app by 10x
That's quite unlikely, unless the native code is throwing exceptions at a very high rate. Something you can easily see in the Output window. What it does do is slow-down the startup of your debug session. The debugger will try to find PDBs for all the native executables, it isn't going to find anything at the Microsoft Symbol Server for SAP code. Simplest way to avoid that delay is using Tools > Options > Debugging > Symbols, untick the "Microsoft Symbols Servers" option.
This question at the SAP support forums would be somewhat comparable. Also the best place to find help with a problem like this. Albeit that it is likely you need support from a SAP escalation engineer, he'll need a small repro project and a minidump of the crashed process.

ExecutionEngineException only when debugging

I have C# code that throws ExecutionEngineException only when I debug it. When I just run it from Visual Studio without debugging (press the "Start without debugging") button, this piece of code works OK. But when I debug it from Visual Studio it throws ExecutionEngineException.
Due to this problem I cannot debug my application, as the code I am trying to debug is executed AFTER the problematic piece of code.
Here are some details:
I am using Visual Studio 2012
The main application is a C++/CLI application that calls my C# code
The application runs for some time until it reaches the problematic lines of code in C#
The relevant code is a query against an Entity Framework context.
I am using Entity Framework 5
The DB where my entities are stored is SQL Server LocalDB (the one that comes with VS2012)
Edit
Further investigation shows that the actual problem is an access violation exception that originates in the default constructor of System.Data.DataSet, which also happens if I just write new DataSet().
Edit 2
I created a small application that demonstrates this problem. The source code can be found here.
You are welcome to compile it and try and run the project Application. It should crash in Adder.cs with ExecutionEngineException when creating a new DataSet. Please note that the debugger should be Mixed and not Managed/Native.
Your C++/CLI code is most likely corrupting the garbage collected heap. A very typical way for unmanaged code to misbehave. This doesn't get discovered until later, like when you new an object or the garbage collector runs. So the code that crashes is completely unrelated to the code that caused the corruption and gives you no hint whatsoever where the bug is located.
There is very little joy in debugging this, it typically takes a thorough code review, lots of unit tests on the unmanaged code and days of debugging to find it. The "crashes only in the debug build" scenario is very common as well, it doesn't mean that there is no heap corruption in the release build. You are a bit lucky that it fails like this, heap corruption is way harder to debug when it occurs in the release build. You'll want to invest in a debug allocator to catch the bug in action, like the one you get out of <crtdbg.h>. This problem in general made garbage collectors a favored way to manage memory.
My condolences and good luck with it.

How to debug code that interacts with low level APIs (like I/O completion ports)?

I wrote a console application that uses Socket's *Async set of methods and it crashes time to time. It doesn't show me where it threw the exception like synchronized code, console just shuts down and I have no idea what have I done wrong.
Is there a way to detect exceptions when it comes to asynchronous operations like this without knowing where to put a try/catch block?
All I need is to know what part of the code makes my application crash.
Edit:
The usual thing with the unhandled exceptions is when you are debugging your code using Visual Studio, it pauses the execution and shows you the line of code that caused the exception (or at least the exception message). But in some situations (e.g. interacting with a low level API like IOCP) your program just crashes and debugging ends with no information about its cause.
What I need is a way to see that particular exception:
"What happened or where (in which method) it happened so my program crashed?"
So I don't ask "What have I done wrong?", I ask "How can I find out what have I done wrong?"
Can I make the execution break at the point where the exception is thrown?
Can I see the call stack after crash to identify the method that caused it?
Could you provide any advice to avoid these kind of situations?
Click Debug-menu -> Exceptions. Make sure Common Language Runtime Exceptions are thrown. Sometimes the IDE unchecks this option. I don't know why, but it's annoying.
Enable System.Net logging to see whats happening underneath

Testing and debuggin application crashes C#

I have an application that after a few times if running it crashes. (application not responding).
when I try to attach my code to process I get assembly debugging, with no helpfull stack trace.
I'm unable to reproduce this from running in VS but only as an application. (therefor intellitrace - which I just read about but not very familiar is irrelevant)
Is there any tool I can use to assist understanding the root cause of the crash
Thanks!
Check the event log or any other logs that your app might be writing to.
Find out if you can narrow down the minimal circumstances to repeat the crash/behavior so you can read the source code to trace the minimal scenario.
If the app does crash when running from VS check whether you are ignoring any exceptions. Look at the Debug | Exceptions dialog and have a look at the output view.
Check your code for Debug.Asserts that are removed from the Release build.
The most common way is to use some kind of Logging system.
Log4Net is very popular these days, you should have a look at it.
Furthermore, if you fix this bug but another one arises on your clients machines, you won't ask them to run a debugger for you, but they can provide you the log file ;-)

C# create a fatal exception?

I have a strange scenario when my application can get into an infinite loop when shutting down. It occurs when it wants to do something but the calls fail as it no longer has access (time based). In such a scenario it should just stop.
I record failed attempts and if the count goes above a certain number in a certain time I throw an exception which I expect to start the JIT debugger and stop the application.
I am not entirely sure why it gets into the loop so I want the JIT window that gives me information like the call stack and application status.
I have exception handling, but what I want is to turn it off and somehow generate an exception that will trigger the JIT debugger, however, all other posts I have found have been for handling exceptions and avoid crashes.
If there is another way at runtime to have the application stop and tell me what is happening I would like to know.
Thanks.
You should try Debugger.Launch() and Debugger.Break() methods (but remember that you should use them only in development environment). You can read more here: http://msdn.microsoft.com/en-us/library/7kzs2ysh.aspx
This line:
System.Diagnostics.Debugger.Launch();
will launch the debugger for you. Give it a try.
I have exception handling
Sounds to me that you have too much of it. Only ever catch specific exception types, never catch Exception. Now you can simply throw any other exception type and your app will bomb with an unhandled exception. Which brings up the JIT debugger dialog on your dev machine, a merciful end on your customer's machine.
Using System.Diagnostics.Debugger is good too, but wrap it with #ifdef DEBUG. Your customer doesn't have one.

Categories

Resources