I'm trying to create a top level exception capture for a debug version of some real-time data capture software and was wondering if there was a top-level exception handler similar to Application.ThreadException that captures ALL exceptions, not just unhandled/trapped ones.
Thanks in advance
If you only want to be notified of all exceptions, you can use the AppDomain.FirstChanceException event.
Note: This is only available in .NET 4.0.
ALL exceptions inherit System.Exception. This would be your top-level that you can trap on.
Related
I canĀ“t find a Application.ThreadException event to listen to on my WCF service. I suppose that this is for WinForms so is there a ThreadException event for WCF services? Or will they end up in AppDomain.CurrentDomain.UnhandledException?
The Application.ThreadException event is only used to "to handle otherwise unhandled exceptions that occur in Windows Forms thread" (emphasis added, MSDN), so it isn't of much help in a WCF service.
Your best bet is to indeed use AppDomain.CurrentDomain.UnhandledException. Note however, that you cannot prevent the process from exiting. This event merely allows you to do some logging or error reporting, before "the system default handler reports the exception to the user and terminates the application." (MSDN).
You many also want to implement your own IErrorHandler. Also, checkout this blog entry about some WCF error handling best practices, while your at it.
It looks like you'll need to implement IErrorHandler:
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx
Then register your handler with your ServiceHost:
http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.channeldispatcher.errorhandlers.aspx
It looks like you can also wire up the IErrorHandlers using a custom attribute as described here: http://msdn.microsoft.com/en-us/library/ms751439.aspx
It depends on your client framework.
WCF faults get thrown as exceptions on the client side, so handle them like any other global exception handler:
Winforms uses
Application.ThreadException
WPF uses:
Application.DispatcherUnhandledException
As Christian states, these are only for exceptions thrown on the "GUI" thread, but WCF will marshal callbacks on a duplex service to these by default I think.
Is it possible to catch an exception from anywhere in a console app that would cause the app to terminate? I'm trying to do this without having and try{} catch{} around everything.
You can use AppDomain.CurrentDomain.UnhandledException event which will catch all unhandled exceptions.
Also check this thread for reference: .NET Global exception handler in console application
Try - catch in your main will not be able to catch exceptions from other threads, for example.
Exceptions "bubble up" to the calling method so having a try-catch block in your Main method is enough to catch everything.
The next important question is what you are going to do with exceptions at top level. Once you are back at that level it is often impossible to make any relevant error recovery except retrying the operation. It is often much better to catch any exceptions that are likely to occur at the site where they are thrown and implement recovery code there.
Go to Debug->Exceptions (Ctrl+D,E) and check appropriate Exception you want to handle. There's an option to break on all 'Thrown' and 'User-unhandled' exception.
You probably want to select 'Common Language Runtime Exception' that are 'Thrown' and 'User-unhandled'. This would break execution any time a CLR exception occurs.
See Most Useful VS Feature No One Knows About
AppDomain.CurrentDomain.UnhandledException += OnCurrentDomain_UnhandledException;
//in windows forms you need also to add these two lines
Application.ThreadException += OnApplication_ThreadException;
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
In a console app you can simply wrap the Main loop in a Try Catch Block. You should know that there are a handful of exceptions that will cause the application to terminate without hitting this block.
Also power failure and setting Environment.FailFast to true will ignore this block.
StackoverflowException msdn docs (You can actually catch it you just shouldn't knowledge here)
Environment.FailFast msdn docs
Check out the AppDomain.CurrentDomain.UnhandledException API for creating an app-global exception handler. And here's a nice blog post about implementing/using it with C# and VB.
Also reconsider your approach to exception handling. Structured exception handling should save you the trouble of needing to deal with 'errors all over the place' because the exceptions percolate up the call stack automatically. This means that if you take advantage of exception handling properly then you will have a small number of points in your code where you handle particular exceptions. You definitely should not try and catch everywhere, all the the time.
A try{} / catch{Exception} in your top-level will catch anything thrown from below before it becomes an "uncaught exception".
First some background: I have a multi-threaded WinForms application that is doing interop to native dlls. This application crashes sometimes with unhandled exception and we are trying to investigate why does it happen. In order to facilitate it, I am creating a global exception handler and I plan to generate process dumpfile from it.
Now coming towards question: as of now this application has handler for Application.ThreadException but it still crashes with unhandled exception. I am thinking of adding a handler for AppDomain.UnhandledException also although I am not sure if its going to help. Are there any possible unhandled exception in this scenario that will not be caught by Application.ThreadException?
Yes, Application.ThreadException can only trap exceptions that are raised in the UI thread. In code that's run due to Windows notifications. Or in technical terms, the events that are triggered by the message loop. Most any Winforms event fit this category.
What it does not trap are exceptions raised on any non-UI thread, like a worker thread started with Thread.Start(), ThreadPool.QueueUserWorkItem or a delegate's BeginInvoke() method. Any unhandled exception in those will terminate the app, AppDomain.UnhandledException is the last gasp.
Going further down-hill, hardware exceptions that are raised in an unmanaged thread by native code that never made any managed CLR call can not be detected with any CLR mechanism. An AccessViolation (exception code 0xc0000005) is the most common cause of death. The only way to trap those is through the Windows API, SetUnhandledExceptionFilter(). This is hard to get right.
You can disable Application.ThreadException with Application.SetUnhandledExceptionMode(). Which is a wise thing to do, giving the user the Continue option doesn't make a lot of sense. Now all exceptions in managed threads behave the same, use AppDomain.UnhandledException to log them.
Application.ThreadException will only be raised for unhandled exceptions on WinForms UI threads (see here.) Adding a handler for AppDomain.UnhandledException could help in this case (though with some caveats, as described in the remarks section here.)
I highly recommend that you use the OS minidump generation instead of your own. This is for several reasons:
Generating a minidump from within the same process is extremely problematic and not always possible.
By the time ThreadException or UnhandledException is started, the exception stack has already been unwound. Generating a minidump at that point will just point you to the handler, not the source of the exception.
If your app is in the field, use WER. If you're doing in-house testing, use ProcDump. You can also just copy the minidump file while the Error Reporting dialog is active.
P.S. There are some exceptional conditions - most notably when doing p/Invoke - where neither ThreadException nor UnhandledException will work.
P.P.S. If you have a debuggable scenario, then try turning on the Managed Debugging Assistants relating to p/Invoke.
I am developing a WPF .net 3.5 application which is using other modules/libraries created within a company. Not all of them support logging and sometimes the information about handled exceptions may be quite useful to find out what's wrong.
So the question is if I can get any notification or hookup somehow for handled events in other modules?
Thanks.
In net 4.0 and above, there is a solution:
The event AppDomain.FirstChanceException fires before any catch block is executed.
This MSDN article has some examples.
Basically you just add an event handler like this:
AppDomain.CurrentDomain.FirstChanceException +=
(object source, FirstChanceExceptionEventArgs e) =>
{
Console.WriteLine("FirstChanceException event raised in {0}: {1}",
AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
};
There are two events, Application.DispatcherUnhandledException and AppDomain.CurrentDomain.UnhandledException, which might help you. Otherwise, I think, you are out of luck, especially if the modules handle the exceptions themself. Only way would be to attach a debugger, as First-Chance exceptions show up there.
I have a single-threaded IronPython WPF application and if an event handler (FrameworkElement.SizeChanged for example) throws, the exception is just eaten and execution continues without any kind of notification.
Because of this I spent a lot of time today solving an "impossible" bug.
Does the same thing happen when using WPF from C#? What happens there if SizeChanged throws?
And is there a way to globally catch exceptions thrown by event handlers, but which don't terminate the application?
A useful trick in c# for catching exceptions globally, is to wrap the entry point for your program in a try-catch block. Any unhandled exceptions will wind their way up to it. Depending on the nature of the exception, it may stop the program from terminating.
EDIT
Thought this might also be relevant to your interests.
WPF global exception handler