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.
Related
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.
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.
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.
I have some places in the C# application where potential Exception's are not catched, but there is a try-finally block to release resources before crashing in case of an Exception.
When I run the code in Visual Studio and an Exception occurs, it breaks at the corrsponding line, marks it yellow and describes the exception.
That's fine.
But after having noticed and read the exception, I want my application to fail savely (execute the finally blocks). This is exactly what would happen if I ran the code outside Visual Studio. However, when I hit F5 to continue, it gets stuck on that very line, marking it over and over again.
What can I do to tell Visual Studio I want the application to continue = fail?
What's happening is you're seeing the Exception Assistant feature of Visual Studio. Whenever there is an unhandled exception in user code it will display to inform the user of the problem.
Unfortunately in certain circumstances it can't be made to go away and you get the behavior you're describing. It's definitely very frustrating when that happens. The best way to work around it is to disable the exception assistant.
Tools -> Options
Debugging -> Generale
Uncheck "Enable the exception assistant"
Sometimes I find I need to hit F5 several times. I know that it will stop on every rethrow or try-block that the exception goes through, so it may be that it is repeating because the exception is happening in a library function and is filtered through several try statements before leaving the library function. VS, however, will just show that library call several times. I've never gotten truly stuck, though. Hitting F5 a few times will get it moving again.
Visual studio will continue on after breaking on exceptions if you do have a matching catch statement for the type of exception being thrown.
However, you can turn off the exception assistant completely for specific exceptions by going to the Debug > Exceptions menu and unchecking the exceptions you would like to ignore.
Please let me know what steps I need to follow when my application crashes and closes showing the dialog containing "Don't send" and "Send error report" buttons.
What can I possibly do other than looking at the event viewer to solve this?
Thanks
You could add a try/catch/finally construct around your Main() entry method's body.
For WinForms, you can add a ThreadException handler, just before Application.Run(), to catch exceptions thrown in WinForms UI event handlers:
Application.ThreadException +=
new ThreadExceptionEventHandler(Application_ThreadException);
All other unhandled exceptions can be caught using:
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
But it's worth mentioning that this only allows you to log/report the exception - you cannot prevent the application from closing once you exit this final handler.
Visual Studio can also be configured to break on first chance exceptions, and external debuggers (like WinDbg with managed SoS extensions) can catch first-chance exceptions too (http://www.codeproject.com/KB/debug/windbg_part1.aspx).
Also, use a logging framework like log4net to add useful logging to your app and dump exception information before the application closes.
Ask your users if they can reproduce the error and how. If you can reproduce the error, run in debug in Visual Studio and follow the steps to cause the crash. Visual studio will enter debug mode where it catches the error. Form there you will be able to follow the stack trace and see what code is causing the error. Visual studio makes debugging pretty easy most of the time.
Ideally you should use a logging library such as nLog or log4net to log any unhandled exceptions, and exceptions in general, by logging them in your code when they occur.
It can also help to have different levels of logging in your application to help you track down a problem when it's not running on your development machine. With nLog you can leave the logging in your production code and enable / disable log output through the use of a logging config file.
I've not used log4net so I don't know if it has a similar feature.
The "send/don't send" errors tend to happen when you have an unhandled exception in a background thread (the main thread will show that continue/quit .NET dialog with a stack trace).
Add an exception handler to your thread's function and log from there:
void RunMyThread()
{
try
{
// background thread code
}
catch (Exception ex)
{
// Log the exception
}
}
This is highly simplified, and may not be how you want to handle an exception. But hopefully this will get you moving in the right direction.
Use WinDBG to debug the issue. You can make it break (as in stop on a breakpoint) when an exception is thrown, and then examine the stacktrace... objects in scope etc...
If it happens at a customer site, and isn't easily reproducable inside a developers debugger, you could do some post mortem debugging. I like to use Userdump to gather a memory dump file (.DMP). Then I use windbg for analysis.