Where do you like to catch exceptions and why?

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

    I like to try and keep my exception handling code separate from my other code so I usually create a helper method that does the actual logic and the outer method just deals with exception handling. I've always thought this gives the code a clean look and makes it more readable.

    public void stuff() throws MyException
    {
        try
        {
            tryStuff();
        }
        catch (SomeLibraryException e)
        {
            logger.log("Some message happened", e);
            throw new MyException(e);
        }
    }
    
    public void tryStuff() throws SomeLibraryException
    {
       // Do things in here that could throw exceptions
    }
    

提交回复
热议问题