Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling in .net web apps

I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop. I'm not being lazy. Far from it. It's that I'm overwrought with exception handling ambivalence. It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill.

I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen.

So, what are your exception handling best practices? In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered?

Sorry for the vague the question but I really want to close the book on this once and for all.

like image 840
NakedBrunch Avatar asked Sep 11 '08 07:09

NakedBrunch


2 Answers

Microsoft's Patterns & Practices team did a good job incorporating best practices of exception management into Enterprise Library Exception Handling Application Block

Event if wouldn't use Enterprise Library, I highly recommend you to read their documentation. P&P team describes common scenarios and best practices for exceptions handling.

To get you started I recommend read following articles:

  • Exception Handling on MSDN
  • Exception Management in .NET on MSDN
  • Exception Handling Best Practices in .NET on CodeProject

ASP.NET specific articles:

like image 94
aku Avatar answered Oct 29 '22 14:10

aku


The golden rule with exception handling is:

"Only catch what you know how to handle"

I've seen too many try-catch blocks where the catch does nothing but rethrow the exception. This adds no value. Just because you call a method that has the potential to throw an exception doesn't mean you have to deal with the possible exception in the calling code. It is often perfectly acceptable to let exceptions propagate up the call stack to some other code that does know what to do. In some cases, it is valid to let exceptions propagate all the way up to the user interface layer then catch and display the message to the user. It might be that no code is best-placed to know how to handle the situation and the user must decide the course of action.

like image 29
Wheelie Avatar answered Oct 29 '22 14:10

Wheelie