Logging unhandled exceptions in a Windows Application to file

Mikexx

Member
Joined
Sep 15, 2021
Messages
6
Programming Experience
1-3
Please be gentle to a C# newbie in Visual Studio.
I have been handed a Windows Forms application using .Net 4.6 and has 3 namespaces, two of which are dll Class Libraries.
I have looked at NLog and gone some way down the path with tutorials and examples. However it seems easy to output handled exceptions to a log file but struggling to output unhandled exceptions.
I've only touched Log4Net but this looks the same. All the example tutorials have a single namespace and no examples of where unhandled exceptions are recorded.

Is there a way I can output unhandled exceptions to a log file, not just in the executable but also from code in the dlls?
 
Solution
You can create a global exception handler by handling the Application.ThreadException and AppDomain.UnhandledException events, both of which are static, and you can then log your unforeseen exceptions there.
First of all may thank the contributors of this thread.

On further examination of the code, there are indeed a try catch block, where the result is effectively discarded. But I could see the exception in the Visual Studio Output tab window, hence the confusion.

In other words these are not unhandled exceptions.

Apologies for wasting contributor's time and thanks again.
 
Perhaps you now realise this but the Output window shows all exceptions that are thrown. The message about a "first chance" exception is when an exception is thrown, without regard for whether it will be caught after that or not.
 
Back
Top Bottom