5

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?

Craig Johnston
  • 7,467
  • 16
  • 40
  • 47
  • possible duplicate of [Handling exceptions, is this a good way?](http://stackoverflow.com/questions/2469822/handling-exceptions-is-this-a-good-way) – John Saunders Mar 22 '11 at 02:20

6 Answers6

7

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.

Michael Younkin
  • 788
  • 6
  • 11
3

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.

Community
  • 1
  • 1
Cameron
  • 96,106
  • 25
  • 196
  • 225
  • I disagree. Even in the case of a web server, if you have an exception that you don't know how to handle, then crash (preferably producing a dump). You need to know _immediately_ that you've got a bug, and you may need the dump in order to fix it. – John Saunders Mar 22 '11 at 02:37
  • @John: I was picturing a web server running other people's code that produced an exception (where you wouldn't want to have to restart the entire server every time some user made a mistake), but I completely agree that failing fast is almost always the best option in general. – Cameron Mar 22 '11 at 02:48
  • that's quite a specific case. Of course, you always need to protect yourself from "the other guy", but if it's your _own_ code throwing an unhandled exception, then crashing is the right thing to do. – John Saunders Mar 22 '11 at 02:55
1

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.

bnieland
  • 6,047
  • 4
  • 40
  • 66
  • 1
    In the case of ASP.NET, simply enabling Health Monitoring will put most of the information you could want into the event log (or other location you configure). – John Saunders Mar 22 '11 at 02:26
1

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.

Sarwar Erfan
  • 18,034
  • 5
  • 46
  • 57
  • 2
    -1: sorry, I totally disagree. _Especially_ in a commercial application, if your product has a bug that you haven't fixed yet, then _crash_, _soonest_, ensuring that the bug is reported to you, so that you can _fix it_. Commercial applications with unfixed bugs, give a bad impression. – John Saunders Mar 22 '11 at 02:38
  • I think you may not have really read the response completely. Real users can and do interpret the built-in crash dialogs as unprofessional (though of course this is a generalization and not all kinds of users will feel this way). From experience I know that this can make the difference between a mildly irritated bug report and a full blown death-threat-I'm-going-to-sue-you-and-your-entire-family type of bug report. It depends on who your users are. It's never okay to try to continue as if nothing happened, but you can go down with a bit more grace while maintaining the info you need to debug. – brewbuck Mar 22 '11 at 03:17
  • @John Saunders: I also feel pity. You are like guarding this question and giving a down vote to all who are suggesting to catch exceptions :) So, how many days have you budgeted for guarding this question? What about you protect this question? – Sarwar Erfan Mar 22 '11 at 03:48
  • @brew: I don't care what crash dialog you use, or if you use any at all. Do not "handle" every possible exception. At worst, have an Application-level handler that logs the error and says something like, "sorry we screwed up, here's a nice message so you won't think we're unprofessional". To my mind, it's the existence of the unhandled exception which is unprofessional, not the built-in crash dialog. – John Saunders Mar 22 '11 at 04:57
  • 3
    just speaking from experience. One of the first things I do on a new project is to get rid of the exception handling. That way, I ensure that I learn about the bugs that the previous developers hid behind a "professional facade". – John Saunders Mar 22 '11 at 04:58
1

MSDN article on the topic:

http://msdn.microsoft.com/en-us/library/ms229005.aspx

Highlights:

Avoid handling errors by catching non-specific exceptions, such as System.Exception, System.SystemException, and so on, in application code. There are cases when handling errors in applications is acceptable, but such cases are rare.

An application should not handle exceptions that can result in an unexpected or exploitable state. If you cannot predict all possible causes of an exception and ensure that malicious code cannot exploit the resulting application state, you should allow the application to terminate instead of handling the exception. ...

You should catch only those exceptions that you can recover from. ...

Do prefer using an empty throw (throw;) when catching and re-throwing an exception. This is the best way to preserve the exception call stack.

MSDN Magazine on Exception Handling changes in .NET 4.0 - "It's Still Wrong to Use Catch (Exception e)" - http://msdn.microsoft.com/en-us/magazine/dd419661.aspx#id0070057

foson
  • 10,037
  • 2
  • 35
  • 53
0

When you think that there might be an issue arising from user interaction with your app in an unintended way, then you must always catch a possible exception, and handle it with relevant error messages.

DrMaxB
  • 540
  • 1
  • 3
  • 13
  • As long as you place the try/catch block around the smallest possible piece of code (the piece that might fail because of the user), then that's ok. My big problem is developers who place try/catch around every method, just because "something" might go wrong. What's most likely to go wrong is a bug in the code. – John Saunders Mar 22 '11 at 05:01