I am calling the following function some where in program that will throw an exception
public static List<Templates> LoadTemplates()
{
// ...
// System.Threading.Thread.CurrentThread.ManagedThreadId == 1 // ID written to log file
System.IO.Directory.GetFiles("does_not_exist_directory");
// ...
}
And I try to catch the exception in the default Program.cs
try
{
// System.Threading.Thread.CurrentThread.ManagedThreadId == 1
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
catch (Exception ex)
{
MessageBox.Show("ERROR CAUGHT");
}
finally { // do clean up }
When run in MSVS, the exception get caught as expected. But when run by double-clicking the .exe in the output directory the exception display in a message dialog stating
EDIT:
To catch the error when running the .exe from output directory, the code must be compiled with handling the Application.ThreadException event
Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.Run(new Form());
But then MSVS will behave undesirably by showing the MSVS native "Troubleshooting Tips" borderless message dialog "Unhandled Exception".
How can I ensure that it behaves the same in and out of MSVS?
The code you have shown will only catch exceptions in the same thread. It's really hard to tell without seeing the offending code and it's context.
You can subscribe to a couple of events to catch all of those:
please read/note the docs (the first one should do) - there are some caveats.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With