Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: should all exceptions be caught

Tags:

c#

exception

Should all exceptions be caught in a C# program, or are some exceptions (such as stack overflow, out of memory etc.) ones that you should allow the program to crash on because there is no way to recover from them?

like image 579
Craig Johnston Avatar asked Mar 22 '11 02:03

Craig Johnston


4 Answers

You should only catch exceptions that you are able to handle. Never ever catch exceptions and do nothing. Do your best to keep the exception from occurring in the first place. This is especially important in .Net because exceptions incur a penalty in performance due to the stack trace.

like image 104
Michael Younkin Avatar answered Oct 06 '22 09:10

Michael Younkin


It depends on the program, of course, but in general, only catch exceptions that you can actually do something about in a meaningful way.

See this question about catching an OutOfMemoryException (you can usually recover from it) and this one about catching a StackOverflowException (generally not possible).

If you're writing a long-running application (e.g. a web server), then of course you'd want to catch all possible exceptions to prevent them from terminating the entire process. If you're writing a low-impact end-user application, then perhaps just logging the exception and failing fast is the best solution.

It's impossible to be (completely) prepared for the unexpected.

like image 33
Cameron Avatar answered Oct 06 '22 11:10

Cameron


Yes, at the very least exceptions should be logged, giving as much intofmation about the state of the system/program at the time of the crash. The Logging Application Block is one of the more robust automatic ways to log errors.

like image 30
bnieland Avatar answered Oct 06 '22 11:10

bnieland


From commercial application development POV, all exceptions should be caught and NONE should be allowed to crash the program. Because, now-a-days, computer users can differentiate between an error message and application crash dialog.

A product that crashes gives bad impression to the customer. When you have no way to recover, you can show an error message politely saying that the app will exit now and the user has to start the app again. Then, gracefully exit when the user presses ok on the modal dialog.

Even sometimes you can give useful information when there is no way to recover. For example, in case of out of memory, you can advise the user to close other applications (if any) before starting this app again.

Though, the end result is same, but a friendly error message gives much better impression than an OS generated crash dialog.

like image 33
Sarwar Erfan Avatar answered Oct 06 '22 10:10

Sarwar Erfan