find all exceptions occuring - c#

I have a large .net application written in C#. I want to check if and what exceptions may be firing in the application that are caught by a try/catch and may not be evident - they are smuggled as such.
Anyway to find such easily? Any setting in visual studio for it?

Go to the Debug / Exceptions menu, and there you can register for exceptions (just check the exceptions you want to monitor).
This way, the debugger will break when they are raised, even if they should be caught later on.

Related

Visual Studio 2015+ C#/.NET Debugger: How to break only on unhandld exceptions?

So, I have found a lot of resources and StackOverflow questions on this exact topic, but it seems to only apply to pretty old versions of Visual Studi0 -- like 2012.
My issue is that I want the Debugger to ONLY break when an exception is UN-HANDLED. The official MSDN says that the Debugger breaks on what is called a "first-chance" exception, meaning that it is intended functionality to break even if the exception is going to be handled.
I find it incredibly annoying to have the Debugger break on an InvalidCastException that I have wrapped inside a try-catch. Is there any way that I can force the Debugger to ignore first-chance exceptions that will be handled? A common answer is to just disable breaking on that particular CLR Exception type, but that's honestly a ridiculous solution. I don't want to suppress the Exception everywhere. I just don't want to be notified that an Exception was thrown when I already guarded against it.
I can imagine your frustration, but there has to be something odd with your VisualStudio settings. I can assure you that on my setups, VS never catches exceptions that are handled, and that is/was true across all VS versions ranging from VS2008 upto VS2015.
"FirstChance exception" line you see in the output window is an information that an exception has been just thrown, at exactly that moment, before any handlers were triggered or stacks unwound.
But that does not imply any breaking in VisualStudio. Only a one-liner is written to the debug output, and program continues - stack is unwound, and nearest matching catch is executed, and program runs forward.
Now, the VS/Debugger/CLR can break on exceptions being throw, but it has to be turned on. You can get there by Debug->Windows->Exceptions, or press CTRL+D+E. When you click that, a new panel should appear, with a list of exceptions and one or two options for each of them:
break when thrown
break on unhandled
but that may vary depending on your VS version. For example, in VS Community 2015, there's only "Break when thrown", and "unhandled" is not visible, but still is active for all of them. You just can't turn off breaking on "unhandled".
Anyways, the important thing is that by default, all "unhandled" are selected, and none or almost none of "when thrown" is. In VS2015Community, I see following "when thrown" set by default:
some C++ "Platform::xxxx" exceptions
System.Reflection.MissingMetadata [<-C#]
System.Reflection.MissingRuntimeArtifact [<-C#]
System.Windows.Markup.XamlParseException [<-C#]
Javascript exception: Access Denied, code 0x80070005
some ManagedDebuggingAssistants: LoaderLock, ContextSwitch, ...
a few Win32 exceptions
and that's all. Maybe total of 10..20 very specific types, I didn't count. In "Common Language Runtime" group only three are checked by default, those listed above. No InvalidCastExceptions.
If your VS is triggering at the moment it is thrown, then it means that you, or someone that had access to your VS, has configured it differently. Most probably, in that "ExceptionSettings" panel, you have "InvalidCastException" marked as "break when thrown". Go there, see the state of the checkbox at "InvalidCastExceptions" and uncheck it, and retry.
If this helps for the case of InvalidCastExceptions, and if this problem happens for some other exceptions as well, then you can repeat it for any other type that you dont want to break-on-thrown. And yes, it means that at some point of time you (or someone else) have clicked there and checked them to break on them.
If you have many of them checked to break-on-thrown, then instead of clicking on each one, you can click on the subtree root and check/uncheck whole groups. (btw. maybe you had accidentaly clicked and checked a whole group a week or month ago?)
Also, there's a very useful "Restore Defaults" underrightclick and even a button called "Restore the list to default settings", both of which simply reset everything to the default settings (like in the list I wrote above: some C++, some reflection, some win32, and so on).
Finally, whatever exceptions you deselect for break-on-thrown in ExceptionSettings panel, VisualStudio will still break on any unhandled exceptions. (unless you see there another set of checkboxes, labelled as "unhandled" - there was such thing in i.e. VS2010Pro, but in VS2015Community I dont see it.. maybe it's a Pro thing)
As of Visual Studio 2015, you can go to Debug -> Windows -> Exception Settings. You define which exceptions to automatically break for on a case-by-case basis. There is also a link to this window when VS breaks for an exception - click on "Exception Settings" at the bottom of the window.
On my home computer, I only see one column, "Thrown", so to your point, there is no way to throw only unhandled exception. At work, though, I have a second column called "User Unhandled", which allows me to do exactly what you're talking about. Leaving "user unhandled" checked and unchecking "thrown" causes it to break only on unhandled exceptions, not on ones that are caught. I think this may be a feature of Visual Studio Professional edition - at home I use Community Edition.
If you use the higher VS version like the VS2015, it has no the option to enable/disable the Unhandled Exception like the Old VS version, but it has his own feature:
So if we just want to capture the unhandled exception, we could disable the checkbox.
Is there any way that I can force the Debugger to ignore first-chance exceptions that will be handled?
I don't want to suppress the Exception everywhere. I just don't want to be notified that an Exception was thrown when I already guarded against it.
But if you still want to get the first change exception messages that will be handled, it has no good workaround for this issue, since at this point the debugger does not know if the exception will be caught (handled) by the application, and if you enable the checkbox, it will capture the first-chance exception(When an exception is first thrown in the application, this is classified as a “first chance” exception).
Reference:
https://blogs.msdn.microsoft.com/visualstudioalm/2015/02/23/the-new-exception-settings-window-in-visual-studio-2015/
https://blogs.msdn.microsoft.com/visualstudioalm/2015/01/07/understanding-exceptions-while-debugging-with-visual-studio/#unhandled.
Remember that you can define your own build configuration next to Release or Debug which can follow the #if <name> and #endif marks in your code. There you can for example decide if you want to focus on exception or not depending on configuration.

Exception control when release an application?

Possibly an obvious question to some but couldn't find a duplicate.
I'm packaging the final version of a Windows Forms solution I've been working on and am getting it ready for online distribution. What are the best practices when doing so? We've already had some trouble with packaging the installation file and have run into hurdles to test the program on different PCs, both 32 and 64-bit included.
More specifically, should "throw;" commands be commented out or left in the final release? Would this expose any of the inner workings of the solution itself?
Released application should not crash when exception occurs. You will want to inform the user, something went wrong and log your exception, but you do not want to crash! Informing user should be done in a friendly manner and not just by putting exception.ToString() into the message box.
It is a good practice to add Application.ThreadException or AppDomain.CurrentDomain.UnhandledException handlers to handle all exceptions in your Application. How exactly to do that, is answered in the following thread: Catch Application Exceptions in a Windows Forms Application
However, make sure that your application survives in a usable state, i.e. handle exceptions in a proper way for your application.
I usually add a preprocessor directive for handling exceptions on the application level, since I want them to trow while debugging. For example:
#if !DEBUG
Application.ThreadException += new ThreadExceptionEventHandler(MyHandler);
#endif
It should also be mentioned, that if you have code pieces where you anticipate that Exception might occur, such as network communication error, you should handle those pieces explicitly. What I am saying is, we should not completely forget about exception handling, just because we configured an unhandled exception handler on the application level.
Keep all of your exception handling intact.
Add an event to the starting form in the application, attaching to the Application.UnhandledException event. This will fire if an exception propogates up the stack.
This is the point to inform the user that the application has crashed. Log the error here and then abort gracefully.
Your point about revealing internals, thats up to you to decide. You can obfuscate the source code if you wish, but if you are releasing in Release build mode, and you are not providing the .PDB, then this is the first step.
Ultimately, the DLL / EXE can be decompiled anyway, so its up to you. Debug mode will reveal a lot more than Release mode, but not much more.
Ideally, you should be catching anything that's thrown higher with throw;. Carefully check your code and try to ensure that thrown exceptions are dealt with appropriately. Unhandled exceptions are logged - you can see this information in the Windows Event Viewer. Depending on what details you put in them, unhandled exceptions could give clues as to the inner workings of your application. However, I would suggest that unhandled exceptions are a poor source of information, and that anyone who wanted to know how your application worked could simply disassemble it, unless you've obfuscated it.
Some exceptions cannot be caught by surrounding code with try/catch blocks, so your application should also implement an unhandled exception handler. This gives you the opportunity to show the user an error message and do something with the exception - log it, send it to support, discard it, etc.

Is it possible to do Vectored Strctured exception handling in c#?

As far as i know, when a first chance exception occurs, the debugger is notified(if any) and then if still unhandled, the system searches for the nearest frame based exception handler in the stack if any.
I was reading this link when I came to know about vectored exception handling.
Question1) I was wondering if there is any way we can do that in managed code?
Question2) I think that any try{}catch{} is a frame based handler but what happens when we register a handle at certain events like
AppDomain.CurrentDomain.UnhandledException += (x, y) =>
{
Console.WriteLine("Unhandled exception");
};
what are these?
The debugger is only notified of an exception if it is attached. For example, if you are debugging in Visal Studio, then it would be called first, and if it passed on the exception, the exception handlers would be called. To have the debugger stop on all exceptions, from Visual Studio select the Debug menu and select Exceptions and then choose the exceptions you want the debugger to halt at. If none of those handlers (or there are no handlers) then the debugger would be called a 2nd time to stop execution and display a general message that an exception had occurred. If on the other hand, the debugger is not attached, then the debugger won't be notified - which is the case for 99%+ of all managed production code.
Vectored exception handling is a low level api intended to be used from unmanaged code - i.e. C++. Your very first choice from managed code (C#) should be to use structured exception handling with try/catch/finally blocks. Most (99%+) managed code developers using a language like C#, including myself, have found structured exception handling to be quite adequate.
If you still think you need to use this api, you will have to call AddVectoredExceptionHandler by using P/Invoke, which is one way unmanaged code can be called from managed code. There are a couple of caveats. See this link for a general overview. Mike Stall's blog suggests avoiding vectored exceptions in managed code. In this thread, Mike Stall says that unmanaged vector exception handlers should never call back into managed code. He also suggests that managed exceptions are an undocumented feature in vectored exception handling and that MS could eliminate that support in a future release of the CLR, so use at your own peril.
The AppDomain.UnhandledException event is only called when no other handler is found. It could be used in situations where it is desired to log some information about an unhandled exception, but there is little time to put in proper structured exception handling to a large base of existing code, or perhaps you don't have access to the code that is throwing the exception. Otherwise, try/catch/finally blocks should be used instead.
You might also try taking a look at the AppDomain.FirstChanceException event, which occurs before the first exception handler is called. This one might be useful if all you want to do is log some information for certain exceptions thrown in someone else's code that you don't have access to that are handled. It is only a notification though, and not an exception handler. I have never used it before, so don't know how much it might affect performance. My concern here is that Microsoft developers sometimes throw exceptions in the CLR for various things other than true errors. To see this in action, try setting the debugger to break on every exception, including the CLR Runtime exceptions. This can be done in Visual Studio from the Debug menu and choosing Exceptions. So, I don't know how much of an impact it would have on performance since all the CLR exceptions will probably raise this event as well. To be fair, the last time I did this was with VS 2008. This might not be true or as true with later versions of the CLR. I don't see a way to limit the exceptions this event will fire either. So, you would need to filter out the exceptions you are not interested in and experiment to guage its impact on performance.

How to Debug better even after using try catch

If I use a try/catch and display a messagebox,I can only see the exception but the VS IDE does not point me to the Exact LINE...(although I get the name of the function and stacktrace)
Is there anyway to throw the exception back on the exact line during debugging without removing the try / catch blocks?
Thanks
In Visual Studio, got to the Debug Menu -> Exceptions...
Make sure 'Thrown' is checked as well as 'User-Unhandled'.
That will make Visual Studio break on the line that threw the Exception even if it is handled (thus pointing you to the exact line).
Turn on first-chance exceptions in the debugger exceptions window. This will hook the selected exceptions at the point they are thrown, regardless of whether they are caught or not.
I should warn you that this can be quite tedious if your application triggers a lot of caught exceptions (which reflects a bad design, anyway).
In case you use VS 2017.
Check either Common Language Runtime Exceptions or one you need from the list below.

Suppressing runtime exceptions in C# for ASP.NET MVC application

How do I suppress an exception in C#? I do not want to enclose it in a try-catch block with an empty catch block - that would defeat the purpose. I have a custom Application_Error handler/listener that checks for HttpException and I would much rather that run automatically than being prompted by Visual Studio for a HttpException and I would have to click Continue in the IDE.
By suppression, I mean to stop this from happening. when the HttpException occurs in my code, a debug exception dialog opens in Visual Studio and my project pauses. Then when I click Continue my Application_Error is able to handle it. I would like it to automatically continue.
In response to Simon's answer, I do not want exception handling turned off globally.
Two Things:
For production: Use ELMAH. Use ELMAH and any Yellow Screen of Death errors get logged.
For Development and YSOD: See this Stack Overflow question that covers your specific issue:
Catching Exceptions within ASPX and ASCX Pages
You can change which exceptions cause the IDE to break by going to Debug -> Exceptions and turn off the Thrown and User-unhandled options for the relevant exceptions.

Categories