After calling a COM-dll component, C# exceptions are not caught by the debugger - c#

I'm using a COM dll provided to me by 3rd-party software company (I don't have the source code). I do know for sure they used Java to implement it because their objects contain property names like 'JvmVersion'.
After I instantiated an object introduced by the provided COM dll, all exceptions in my C# program cannot be caught by the VS debugger and every time an exception occurs I get the default Windows Debugger Selection dialog (And that's while executing my program in debug mode under a full VisualStudio debugging environment).
To illustrate:
throw new Exception("exception 1");
m_moo = new moo(); // Component taken from the COM-dll
throw new Exception("exception 2");
Exception 1 will be caught by VS and show the "yellow exception window".
Exception 2 will open a dialog titled "Visual Studio Just-In-Time Debugger" containing the text "An unhandled win32 exception occurred in myfile.vshost.exe[1348]." followed by a list of the existing VS instances on my system to select from.
I guess the instantiation of "moo" object overrides C#'s exception handler or something like that. Am I correct and is there a way to preserve C#'s exception handler?

Well, that's not good. You however haven't proven yet that the CLR's exception handling logic is completely borked. What you describe could also be explained by something detaching the debugger. The Java JVM would certainly be a candidate. Check if a try still works, if it does you still stand a chance to use this COM server.
Debugging is however going to be painful. With some luck, the detach happens only once. Try writing System.Diagnostics.Debugger.Break() after the very first call to the server, click "Debug" on the dialog you'll get.
Also test if a null reference exception still works, that's a hardware exception that's liable to be redirected by a VM calling Windows' SetUnhandledExceptionFilter(). If that can't be caught then you should not use this COM server as-is, it will destabilize your process too much. Running it in a separate process and talking to it with WCF or Remoting is a desperation move that could work out.
Needless to say, this component vendor is violating the COM server contract badly. You shouldn't have to put up with it.

Adding the following line (as the first line) in my main() (in Program.cs file) made exceptions work again:
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
The above line overides the Automatic handler which (I guess) for some reason stopped working after using the COM component.

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.

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

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.

Finally Block Not Running?

Ok this is kind of a weird issue and I am hoping someone can shed some light. I have the following code:
static void Main(string[] args)
{
try
{
Console.WriteLine("in try");
throw new EncoderFallbackException();
}
catch (Exception)
{
Console.WriteLine("in Catch");
throw new AbandonedMutexException();
}
finally
{
Console.WriteLine("in Finally");
Console.ReadLine();
}
}
NOW when I compile this to target 3.5(2.0 CLR) it will pop up a window saying "XXX has stopped working". If I now click on the Cancel button it will run the finally, AND if I wait until it is done looking and click on the Close Program button it will also run the finally.
Now what is interesting and confusing is IF I do the same thing compiled against 4.0 Clicking on the Cancel button will run the finally block and clicking on the Close Program button will not.
My question is: Why does the finally run on 2.0 and not on 4.0 when hitting the Close Program button? What are the repercussions of this?
EDIT: I am running this from a command prompt in release mode(built in release mode) on windows 7 32 bit. Error Message: First Result below is running on 3.5 hitting close after windows looks for issue, second is when I run it on 4.0 and do the same thing.
I am able to reproduce the behavior now (I didn't get the exact steps from your question when I was reading it the first time).
One difference I can observe is in the way that the .NET runtime handles the unhandled exception. The CLR 2.0 runs a helper called Microsoft .NET Error Reporting Shim (dw20.exe) whereas the CLR 4.0 starts Windows Error Reporting (WerFault.exe).
I assume that the two have different behavior with respect to terminating the crashing process. WerFault.exe obviously kills the .NET process immediately whereas the .NET Error Reporting Shim somehow closes the application so that the finally block still is executed.
Also have a look at the Event Viewer: WerFault logs an application error notifying that the crashed process was terminated:
Application: ConsoleApplication1.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Threading.AbandonedMutexException
Stack:
at Program.Main(System.String[])
dw20.exe however only logs an information item with event id 1001 to the Event Log and does not terminate the process.
Think about how awful that situation is: something unexpected has happened that no one ever wrote code to handle. Is the right thing to do in that situation to run even more code, that was probably also not built to handle this situation? Possibly not. Often the right thing to do here is to not attempt to run the finally blocks because doing so will make a bad situation even worse. You already know the process is going down; put it out of its misery immediately.
In a scenario where an unhandled exception is going to take down the process, anything can happen. It is implementation-defined what happens in this case: whether the error is reported to Windows error reporting, whether a debugger starts up, and so on. The CLR is perfectly within its rights to attempt to run finally blocks, and is also perfectly within its rights to fail fast. In this scenario all bets are off; different implementations can choose to do different things.
All my knowledge on this subject is taken from this article here: http://msdn.microsoft.com/en-us/magazine/cc793966.aspx - please note it is written for .NET 2.0 but I have a feeling it makes sense for what we were experiencing in this case (more than "because it decided to" anyways)
Quick "I dont have time to read that article" answer (although you should, it's a really good one):
The solution to the problem (if you absolutly HAVE to have your finally blocks run) would be to a) put in a global error handler or b) force .NET to always run finally blocks and do things the way it did (arguably the wrong way) in .NET 1.1 - Place the following in your app.config:
<legacyUnhandledExceptionPolicy enabled="1">
The reason for it:
When an exception is thrown in .NET it starts walking back through the stack looking for exception handlers and when it finds one it then does a second walk back through the stack running finally blocks before running the content of the catch. If it does not find a catch then this second walk never happens thus the finally blocks are never run here which is why a global exception handler will always run finally clauses as the CLR will run them when it finds the catch, NOT when it runs it (which I belive means even if you do a catch/throw your finally blocks will still get run).
The reason the app.config fix works is because for .NET 1.0 and 1.1 the CLR had a global catch in it which would swallow Exceptions before they went unmanaged which would, being a catch of course, trigger the finally blocks to run. Of course there is no way the framework can know enough about said Exception to handle it, take for example a stack overflow, so this is probably the wrong way of doing it.
The next bit is where it gets a bit sticky, and I am making assumptions based off of what the article says here.
If you are in .NET 2.0+ without the legacy exception handling on then your Exception would fall out into the Windows exception handling system (SEH) which seems pretty darn similar to the CLR one, in that it walks back through frames until it fails to find a catch and then calls a series of events called the Unhandled Exception Filter (UEF). This is an event you can subscribe to, but it can only have ONE thing subscribed to it at a time, so when something does subscribe Windows hands it the address of the callback that was there before, allowing you to set up a chain of UEF handlers - BUT THEY DON'T HAVE TO HONOR that address, they should call the address themselves, but if one breaks the chain, bap, you get no more error handling. I assume that this is what is happening when you cancel windows error reporting, it breaks the UEF chain which means that the application is shut down immediately and the finally blocks are not run, however if you let it run to the end and close it, it will call the next UEF in the chain. .NET will have registerd one which is what the AppDomain.UnhandledException is called from (thus even this event is not guaranteed) which I assume is also where you get your finally blocks called from - as I can't see how if you never transition back into the CLR a managed finally block can run (the article does not go into this bit.)
I believe this has something to do with changes to how the debugger is attached.
From the .NET Framework 4 Migration Issues document:
You are no longer notified when the debugger fails to start, or when there is no registered debugger that should be started.
What happens is that you choose to start the debugger, but you cancel it. I believe this falls under this category and the application just stops because of this.
Ran this in both release and debug, in both framework 3.5 and 4.0, I see "in Finally" in all instances, yes running it from command line, went as far as closing my vs sessions, maybe it's something on your machine or as Kobi pointed out, maybe platform related (I'm on Win7 x64)

Debugging in failing method when invoked from other thread

I have code like the one in this question, basically a UI-thread that gets updated from another thread and uses InvokeRequired() and Invoke(..). Now, if the method fails in the work part, the debugger stops on the Invoke(..) line -can I make it show me the line where it actually failed like it usually does?
Have you tried having the debugger break on exceptions (in the VS menus: Debug -> Exceptions, navigate to "Common Language Runtime Exceptions" and optionally dig down to a specific exception type, check the Thrown check box)? This will cause the debugger to break at the code line where the exception is thrown. I think this works also in multithreaded scenarios.
What you're likely running into is an issue with Just My Code (JMC). This is a feature of the debugger where it tries to limit items like unhandled exception notification to only code that is owned by the user instead of the framework. Try disabling this feature and breaking on thrown exceptions and that should take you to the source of the problem.
Disabling Just My Code
Go to Tools -> Options
Navigate to Debugger -> General
Uncheck the Just My Code option

Categories

Resources