Freigeben über


When to catch all exceptions?

One of the general guidelines of exception handling in .Net is to catch the exceptions that you know how to handle and not to catch all exceptions. Even if you intend to re-throw the exception and know the difference between throw ex and throw, it is still better not to do it since throw does modify the stack trace slightly.In reality, this is not easy to follow because you can only rely on documentation about the exceptions a C# method may throw. Documentation is, well, just documentation. However, there is at least one case that it is better to catch all exceptions. That is when the caller does not have a concept of exception at all. For example, you write a component to be consumed through .Net interop by a COM component. Because the exception will be converted to a HRESULT and there is no guarantee that the caller will check the HRESULT, COM interop is effectively "swallowing" the exception. In this case, I found it is much better to catch all exceptions in the .Net method and do some assertion and logging.