Gorden Gram Gorden Gram - 1 year ago 115
C# Question

How to catch all exceptions in c# using try and catch?

I want to write some try and catch that catch any type or exception, is this code is enough (that's the way to do in Java)?

try {
catch (Exception ex){}

Or should it be

try {
catch {}


Answer Source

Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex is declared but not used.

But note that some exceptions are special and will be rethrown automatically.

ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.


As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:

  • Catch and ignore a specific exception that you know is not fatal.

    catch (SomeSpecificException)
        // Ignore this exception.
  • Catch and log all exceptions.

    catch (Exception e)
        // Something unexpected went wrong.
        // Maybe it is also necessary to terminate / restart the application.
  • Catch all exceptions, do some cleanup, then rethrow the exception.


Note that in the last case the exception is rethrown using throw; and not throw ex;.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download