Where do you like to catch exceptions and why?

前端 未结 9 1478
别跟我提以往
别跟我提以往 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:29

    In C# and Java I prefer to not catch exceptions at all. If I can't avoid it, I rethrow a RunTime-exception immediately.

    I'll always use the greediest catch block that has the largest scope needed, but always with the most specific exception-type possible. Since the outcome of the catch block is another throw in 99.99% of the cases, I try to keep the full method within the try block.

    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2020-12-03 09:32

    I always put a catch in main() as a catch of last resort:

    int main( int argc, char** argv ) {
        try {
            Application application( argc, argv );
            return application.result();
        }
        catch ( const std::exception& exception ) {
            fprintf( stderr, "%s.\n", exception.what() );
        }
    }
    
    0 讨论(0)
提交回复
热议问题