-5

I always wonder at what levels of my application whoudl I write try-catch?

DAL? Cache? BL? UI-Logic?

If I write to log and re-throw it

should I use try-catch in every function?

aswuming any function can have an exception I didn't think of

Elad Benda
  • 35,076
  • 87
  • 265
  • 471
  • 3
    Wherever you need them. This question is too broad to answer, I think. – zimdanen Feb 06 '13 at 16:00
  • Here's some info: http://stackoverflow.com/a/1080190/128217 – zimdanen Feb 06 '13 at 16:01
  • This is sort of a general question (See [this](http://msdn.microsoft.com/en-us/library/vstudio/ms229005(v=vs.100).aspx) and [this](http://www.codeproject.com/Articles/9538/Exception-Handling-Best-Practices-in-NET)) and has been asked [several times.](http://stackoverflow.com/search?q=exception+handling+.net+) – gideon Feb 06 '13 at 16:02
  • There is no definitive answer to your question. Might be worth consulting Microsoft's [Best Practices for Handling Exceptions](http://msdn.microsoft.com/en-us/library/seyhszts.aspx). – Kevin Brydon Feb 06 '13 at 16:03
  • http://codereview.stackexchange.com/questions/3773/place-try-catch-in-business-logic-or-user-interface – Win Feb 06 '13 at 20:57

2 Answers2

1

Well, it depends. In the UI layer, I catch all errors globally in Application_Error, and handle these accordingly. I only then try-catch errors that I do not want to bubble up to the UI and cause a redirection to the generic error page. This has been effective for me in reporting most, if not all, errors.

Some people handle errors differently; they'll catch errors in the business layer, and either log and return them from the BLL, or log and rethrow a generic error. For instance, check out how the Enterprise Library Exception block approaches errors.

You can even use AOP library like PostSharp to attach to all the objects you want to handle errors for, or use MVC's exception filtering for handling errors too.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
0

I personally tend to use way more try-finally than try-catch blocks (except for some external Data sources calls)

I keep try-catch for endpoint of my code, where I can log the error stack, and deal with error messages if necessary.

On a side note, be sure to just call throw; so as not to swallow any exception.

Vinzz
  • 3,968
  • 6
  • 36
  • 51