I know it is not good practice to catch System.Exception unless on the top level of an application. What about a thread? Is it okay to catch System.Exception on the top level of the thread?
Update:
The thread is a long running thread that should only be terminated when the application stops. So in order to make sure that the application does not crash I simply catch System.Exception and log the error. Everything is recreated.
while (Terminate == false)
{
var discoveryClient = new DiscoveryClient(new UdpDiscoveryEndpoint());
try
{
var criteria = new FindCriteria(typeof(T));
criteria.Scopes.Add(new Uri(Scope));
var discovered = discoveryClient.Find(criteria);
discoveryClient.Close();
discoveryClient = null;
// do something with the endpoints
}
catch (OutOfMemoryException e)
{
m_Logger.LogException(e, "Exception when trying to discover clients (Contract: {0})", typeof(T).Name);
throw;
}
catch (Exception e)
{
m_Logger.LogException(e, "Exception when trying to discover clients (Contract: {0})", typeof(T).Name);
if (discoveryClient != null)
(discoveryClient as IDisposable).Dispose();
}
}
It depends on what the thread is doing and the context of the thread in your application. Generally speaking, you should follow the golden rule of thumb: do not catch an exception unless you know how to handle it. (I am simplifying of course, but it’s a rule of thumb).
Since we are talking about
System.Exceptionand not some subclass, I assume that you would not in fact know how to handle the exception. Logging the error and letting the application terminate (the only legitimate reason to catch an exception you can’t handle) can be done without catching the exception from within the thread that raised it, so the short answer is no, it’s no OK.If I remember correctly .NET 1 actually caught and swallowed all exceptions raised on background threads. This led to so many problems in badly written programs that MS changed the behavior in .NET 2 to let the exceptions crash the app — and you can imagine they had very good reason to make such a breaking change.
Update regarding
BackgroundWorker:Please do not mistake the usage model of
BackgroundWorkerfor “swallowingSystem.Exceptionis OK”. Here’s what the docs forBackgroundWorker.RunWorkerCompletedsay:Choosing to disregard this suggestion or ignoring the return value on purpose (otherwise an exception will still be thrown!) is, simply put, bad programming practice.