Where to put try catch

前端 未结 11 642
一整个雨季
一整个雨季 2020-12-09 03:51

Consider this scenario: I have 3-layer app, when the user click on the button the button event handler calls a method in biz layer that do whatever with data my button even

相关标签:
11条回答
  • 2020-12-09 04:50

    When I have a multi-layer architecture like this (which is a lot) I will often have a try/catch at more than one layer. For example, a try/catch in the persistence layer that catches an SQLException, does what the persistence layer needs to do (like notify an admin, for example) then throws a new exception that will make sense to some code that calls the persistence layer. An example might be PersistenceException. The next layer up doesn't care about who should be notified to re-start the database, but it does care that it couldn't save user state, so it might catch the PersistenceException and tell the user that his new phone number wasn't stored in the database.

    0 讨论(0)
  • 2020-12-09 04:52

    definitely put a try catch closest to the user -- because in that location you can translate it into something meaningful for your user.

    Deeper try catches could only be needed if you intend to do something with them -- for example, handle the exception, or perhaps log and rethrow the exception.

    0 讨论(0)
  • 2020-12-09 04:54

    You only want to use try catches to manage unhandled code. An example is I have a COM object I am communicating with and I don't want it to stay open and create a memory leak. The other acceptable alternative is to catch errors on events in your database before allowing the exception to continue.

    You do not ever want to use try catches to handle situations where you are unsure you code will work and want a backup plan.

    So where does that leave you when apps blow up, use custom error pages to indicate a problem has occurred in your web apps and for thick clients parse code off into worker threads so they don't blow up your main thread if they fail. Good luck!

    0 讨论(0)
  • 2020-12-09 04:55

    The general answer would be: catch anytime you can handle what is being thrown. That is, the decision is quite simple. For example, catch exceptions that arise when creating an object you need.

    0 讨论(0)
  • 2020-12-09 04:56

    We follow

    Do not catch exceptions if you do not know what to do with it.

    We never handle any exceptions which we cannot handle or default. It gets bubbled up and we handle it at the application level.

    Say if you can default a value, for a businesss object, then you can handle it in the business layer.

    0 讨论(0)
提交回复
热议问题