What should be the best Exception Handling Strategy

后端 未结 7 2017
逝去的感伤
逝去的感伤 2021-02-14 07:28

I am working on application where user invokes a method from UI , on this I am calling a method from business class which calls another methods

UI--> Method1 -->Method2

相关标签:
7条回答
  • 2021-02-14 08:28

    As a rule of thumb, exceptions should only be used for exceptional cases. That is, if you expect a method call to fail sometimes, you shouldn't use exceptions. If there are several possible outcomes, you could use an enumeration:

    public enum AddCustomerResult
    {
        Success,
        CustomerAlreadyExists,
        CustomerPreviouslyRetired
    }
    

    You'd still get exceptions thrown, for database-unavailable errors, and the like; but you'd be testing for expected (albeit possibly rare) cases and indicating success/failure/etc as required.

    This is just one technique that works well for me.

    With exceptions you want to throw them in exceptional circumstances and anywhere where there is a layer traversal (my own convention, don't know how correct it is) you'd want to catch exceptions and rethrow with a custom wrapper class for that layer.

    For example, in the DAL you'd want to catch exceptions and rethrow them as an inner exception on a DataAccessException perhaps; on a web service you'd wrap all your methods in exception handlers to rethrow with a MyWebServiceException. At the UI (which traverses the from inside the app to the user's screen) you'd want to catch, log and give them a nice message. As far as I can see no reason to catch or rethrow anywhere else.

    It gives you an opportunity to hide the underlying exception (which you likely don't want to expose to the caller: e.g. database errors), log in centrally, and provide a common repeatable failure mode.

    In your example, you'd catch exceptions at the UI level only; because if a UI operation fails you don't want the app to crash out with an unhandled exception.

    Hope that helps!

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