Where do you like to catch exceptions and why?

前端 未结 9 1489
别跟我提以往
别跟我提以往 2020-12-03 08:31

Where do you like to catch exceptions and why?

I\'m interested in seeing where people find it useful to put their try/catch blocks in the hope that some general patt

9条回答
  •  心在旅途
    2020-12-03 09:30

    (Before I begin: I am a Java guy)
    What I recommend:

    1. Find the closest point up the call chain from the exception source where you can handle the exception properly - i.e take corrective measures, signal failure of the transaction/action etc. (Logging by itself should not be considered as handling the exceptions) All the methods between the handler and the thrower should ignore the exception. Prefer unchecked exceptions to checked ones so that the exceptions don't even figure in all those intermediate methods.
    2. Layer boundaries and APIs should specify the exceptions it can throw using checked exceptions since handling those exceptions is part of the contract for the client layer/code that uses it.
    3. Write an exception handler class with a handle(Exception e) method and release that to the team initially and ensure that everyone uses it to handle exceptions. Based on changing exception handling scenarios, keep adding overloaded 'handle' methods later on so that only the handler need to be modified.
    4. Always remember to chain exceptions when doing catch-and-throw. This ensures that the full cause of exception gets reported.
    5. Never log the same exception trace more than once. It makes it very hard to debug using log files.
    6. Top level methods should have a catch clause that will catch any exception that the system may throw. This prevents spilling of our internal information to the outside world if, god forbid, things go wrong in production environment. This is more of a security requirement.

提交回复
热议问题