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

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

Related

Intentionally cause a fatal exception

I need to create a fatal exception on demand, using C#. While I have done this unintentionally enough times, now I need to, I can't find a simple way.
It's easy enough to cause a null reference error or divide by zero etc., but I need something which will CTD without giving the option to continue.
Thanks for your help.
Don't use an exception to accomplish this, it has too many side-effects. Including not terminating the program at all, whether an unhandled exception ends the program is a CLR policy that can be changed. Both by a custom CLR host and still exposed today by the legacyUnhandledExceptionPolicy config attribute.
The most reliable way to instantly abort a program, without any events getting fired and without any cleanup (including not running finalizers) is Environment.FailFast().
IMHO I prefer a milder approach. I create a custom Exception that I call FatalException. https://learn.microsoft.com/en-us/dotnet/standard/exceptions/how-to-create-user-defined-exceptions. That way when I call methods that throw FatalException, I simply do a try-catch around the call and catch (FatalException fe). I usually re-throw as necessary to get back to parent form which also has a the final catch for the FatalException exception and then log it (I use Log4Net), show a messagebox as to the reason for the Fatal situation and call my overridden Dispose() method and exit the application gracefully. Obviously this becomes more difficult the deeper your nested calls. The extra work is worth the extra grace to me. If this becomes a standard in your application, you will understand it when you encounter it and ensure that you don't break it. I put my Custom Exceptions in a DLL library. If your code is in a library, this approach still works because the Exceptions are also in a library they can be shared by both another library and the main application. This means your library can throw a FatalException as well, although the reasons for doing so should be few a far between.

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.

Prevent Stack Overflow Exception from crashing process

Assume I have an application, where user can provide script written in JavaScript to perform some task in it. This is done using Jint. However, badly written script can cause Stack Overflow Exception in JintEngine.Run() and therefore crashing whole application. I would rather like to inform user about the error in script.
I tried to run Jint on another application domain, that did not help, cause AFAIK default action on SOE is exiting process. Could be it changed any other way than by using CLR hosting?
I know I can run separate process and that's my fallback, nevertheless I would like not to do that.
As you suspected, it's just not possible to catch a StackOverflowException generated by the runtime unless you're hosting the CLR yourself [1]. As the Microsoft documentation suggests, your best bet is to try and detect the stack overflow before it happens.
In the case of using Jint, this means finding some way to hook into the execution engine and attach your own code to arbitrary method calls. Fortunately, a brief overview of their documentation reveals that they have a debugging mode that does just that! [2]
No doubt running in debugging mode means slowing down your script execution; it's up to you to decide if the benefit of detecting overflows is worth the penalty--and I definitely suggest measuring that penalty to ensure it's really going to be a problem. One possible mitigation would be to allow the user to choose when debugging mode is active.
-Mark
[1] http://msdn.microsoft.com/en-us/library/system.stackoverflowexception.aspx (see remarks)
[2] http://jint.codeplex.com/wikipage?title=Debugging&referringTitle=Documentation

Wouldn’t handling an exception be a better idea

1)
1 - Only handle exceptions that you
can actually do something about, and
2 - You can't do anything about the vast majority of exceptions
a) I assume that “By not handling an exception” the text is suggesting that we should let the exception bubble up the stack, where runtime will abort our application?!
b) But why is letting the runtime abort the exception preferred over catching an exception, logging it and then informing the user of failure? Only difference between the two is that in the latter case application isn’t aborted
For example, if database goes down, why should the whole program crash ( due to not handling an exception ), if we can instead catch the exception, log it and notify user of failure and that way we can keep the program up and running
2) If you know that exception potentially raised by some block of code can’t be handled, should you include this code inside a try-finally block or is it better to leave it outside any try-finally blocks?
Thank you
No, the guideline is not to catch an exception you cannot do anything about except at the top-level of your application or thread.
You should try to avoid letting your application crash - log the information somewhere, give a message to your user explaining what happened, and tell them how to report the error to you. Perhaps also try to save their unsaved data in a recovery file so that the next time the application starts it can offer the option to attempt to recover their lost work.
Try looking at it this way... The database goes down. How do you know? Because you get an timeout/an exception/something. But your application probably isnt getting the exception. ADO.NET/Linq to SQL/Entity Framework/Whatever data provider you are using is actually getting the exception and throwing it to your application. To me, this is what that advice is advising: as a component designer, prefer to throw exceptions you can't do anything about.
For the database down example, is there anything the ADO.NET data provider can do? Can it bring a server back up? Repair network connections? Reset permissions? No. So it doesn't handle the exception, it throws it.
The guideline you cite is for component development, not the outer edge of a run-time boundary (a thread or application). At that level, it would be correct to make a decision on how to handle exception that have bubbled that far.
I think the person you are quoting suggests that you should let the exception bubble up the stack until something higher up can make sense of it or until it reaches the top of the call stack where you do have code that would log it, or display a error message to the user then exit your program if it is fatal, or carry on if it is not.
Sometimes it may be better to not continue executing the program - if you get a OutOfMemoryException for example or some other situation where the programs actions are undefined - a potential disaster.
I think the key to
Only handle exceptions that you can actually do something about
is that you should only handle the exception if you can carry on from that point in your application.
To take a trivial example.
If you're looking for a file on the user's system and it's not there when it should be you should raise the "file not found" exception. Now if you can recover from this (say by simply recreating the file) then do so and carry on. However, if the file can't be recreated then you shouldn't let your program carry on.
However, this doesn't mean you can't have a top level catch all exception handler in your main program to display a friendly message to the user, perhaps to log the exception or even mail it to you the developer.
That statement holds true. But it is a reference to catching exception in the deeper layers of application. Basically most of the code we write does not need exception handling. It is only the client part of the application is responsible for catching the error and presenting it to the user - as well as logging.
For example, the same business code/database code can be used in a web application and windows/wpf application and logging/handling could be different and deeper layers do not know about how this will be handled so they need to leave the responsibility to the UI tier.
The point is that you don't want to have try/catch blocks nested everywhere in your code as this tends to hide issues with your code. It is better to only implement exception handling where you understand the error and the desired outcome, else don't handle it and let it bubble up.
As for as the errors bubbling up, you should have a global exception handler for these uncaught application errors. This is only implemented in one spot in your app and will allow you to log or present the error to the user. Again this is only implemented in one spot in your app, and is implemented by hooking the application.error event.
Event to hook in .net win forms application:
AppDomain.CurrentDomain.UnhandledException
Event to hook in .net asp.net application:
HttpApplication.Error
Enjoy!
Without knowledge about the context of both statements, stated that both statements apply to methods and classes then they make sense:
A piece of code which calls a method can only handle exceptions for which it has enough information about the context. In most cases a piece of code won't have enough information, to handle all exceptions.
Example: A piece of code, which calls a method SaveData() can handle a DatabaseStorageException when it knows, that it saves data to a database. On the other hand, if the piece of code is programmed in a storage agnostic manner, than catching such a specific exception is not a very good idea. In this case it is better to let the exception pop up the callstack and let some other code handle the exception, which has enough context information to handle it.

How to prevent exceptions bubbling up in C#?

If I'm writing a class library, and at some point in that library I have code to catch an exception and deal with it, then I don't want anyone using my library to know that it even happened - it should be invisible from the outside world.
However, if they have "Catch Thrown Exceptions" turned on in Visual Studio (as opposed to "Catch User Unhandled Exceptions") then the exception will be visible to them.
Is there any way to avoid this?
No. This is by design: as a developer, I run with "Catch Thrown Exceptions" turned on, so that I can see exceptions thrown in library code (and hopefully avoid them). The situation you're in applies equally to the .NET framework's own libraries too.
The best way would be to avoid throwing the exception in the first place. As a side benefit, you library code will be faster, since throwing an exception has a noticeable impact on performance (and should only be used in 'exceptional' circumstances).
The only way you can pull this off is if you put a [DebuggerHidden] attribute on the method that may throw the exception. Like others have pointed out, better to avoid the exception altogether, but this attribute will accomplish what you want.
You cannot prevent this. Someone can always attach an debuger to the process and monitor what is going on.
You could just remove the exception and provide the error handling yourself, but I would really not recommend that because it is some kind of reinventing the wheel - recreating the exception handling system.
The said applies of course only if the code throwing and the code catching the exception are far apart and quite unreleated. If they are tightly coupled, you should really check if the call can succeed and only call in this case. Always remeber that exception are intended for exceptional cases - not for normal control flow where you could check if the operation can succeed
As Tim Robinson suggests there is no way to control someone viewing exceptions thrown from your library. His answer is good so I won't rehash it.
There are a couple of posts here on SO that you may find helpful when addressing (what sounds like) using exceptions as program flow control:
Catching exceptions as expected program execution flow control?
Why are .Net programmers so afraid of exceptions?

Categories

Resources