Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime exception catching different between inside and outside of MSVS

Tags:

c#

exception

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?

like image 381
Jake Avatar asked Oct 10 '22 21:10

Jake


1 Answers

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:

  • AppDomain.UnhandledException
  • Application.ThreadException

please read/note the docs (the first one should do) - there are some caveats.

like image 156
Random Dev Avatar answered Oct 14 '22 00:10

Random Dev