When I first started programming in .NET I used try/catches all the time. I am finding lately though I rarely ever use them for web applications. My exception (no pun intentended) is unmanaged code that could potentially create a memory leak such as com objects. Are they really needed anymore or do they just clutter things up?
UPDATE: Assume custom errors are being used to take care of the ugly stack trace page.
I find that junior programmers use try/catch WAY too heavily. The decision to use try/catch should boil down to these simple rules:
can you handle the error? (perhaps this means to try again, or use different settings, return substitute values, etc)
can you provide a better error message (more detail) ?
do you need to log this specific error? (keep in mind that all errors should be logged at the highest level — for example in the global.asax file in Application_Error method)
do you need to clean up/dispose resource used within an operation, such as a database connection or transaction?
If you answered yes to any of these, then sure, use try/catch. If you said no, then you can safely just allow an error page to be displayed and have the global error handler log it.
If you do intend to log or clean up resources, but still let the exception pass through, make sure you use
throw;and not create a brand new exception. Doing so will eliminate your stack trace and basically give the error no context.Just found this excellent quote from Ayende that seems to put it very nicely: