Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

exception

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 { code.... } catch (Exception ex){} 

Or should it be

try { code.... } catch {} 

?

like image 621
Gorden Gram Avatar asked Oct 16 '12 09:10

Gorden Gram


People also ask

Can you catch exceptions in C?

C itself doesn't support exceptions but you can simulate them to a degree with setjmp and longjmp calls.

How do you catch multiple exceptions with a program?

Handle Multiple Exceptions in a catch Block In Java SE 7 and later, we can now catch more than one type of exception in a single catch block. Each exception type that can be handled by the catch block is separated using a vertical bar or pipe | .

How would you catch multiple exceptions at once in C #?

In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.

Which type of catch block is used to catch all types of exceptions in C?

2) There is a special catch block called the 'catch all' block, written as catch(…), that can be used to catch all types of exceptions. For example, in the following program, an int is thrown as an exception, but there is no catch block for int, so the catch(…) block will be executed.


1 Answers

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.

http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx


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.     Log(e);     // Maybe it is also necessary to terminate / restart the application. } 
  • Catch all exceptions, do some cleanup, then rethrow the exception.

    catch {     SomeCleanUp();     throw; } 

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

like image 85
Mark Byers Avatar answered Oct 06 '22 11:10

Mark Byers