Reputation: 2292
My .NET Windows Forms app has various commands calling my command functions that can throw exceptions handled by my handler at Application.ThreadException. I would like this handler to terminate the command function without terminating the app, even in the case of a command function that has no try/catch. What's the best way to get this?
Thanks.
Upvotes: 0
Views: 53
Reputation: 35895
Another suggestion is to use a Task
class (as it supports Cancelation)
Upvotes: 1
Reputation: 1499740
The simplest approach would be to wrap each of your "commands" in its own try/catch block, which you can do in a fairly generic way. Just catch the exception before it hits the message loop. So if before you had:
public void ClickHandler(object sender, EventArgs e)
{
ExecuteCommand("foo");
}
you'd have:
public void ClickHandler(object sender, EventArgs e)
{
ExecuteInTryCatch(() => ExecuteCommand("foo"));
}
private static void ExecuteInTryCatch(Action action)
{
try
{
action();
}
catch (Exception e)
{
// Log exception
}
}
It's worth noting, however, that catching all exceptions isn't usually a good idea. If you can, catch very specific exceptions instead.
Upvotes: 0