Multiple try-catch or one?

前端 未结 11 1754

Normally, I\'d do this:

try
{
    code

    code that might throw an anticipated exception you want to handle

    code

    code that might throw an anticip         


        
11条回答
  •  难免孤独
    2020-12-08 09:42

    You're thinking about this the wrong way. What do you need to do in your catch blocks? If you would recover from any of the possible exceptions by running the same code, no matter which operation threw the exception, then use one catch block. If you need to do different clean-up operations depending on which operation threw, then use multiple catch blocks.

    Also, if you can use try/finally or the RAII pattern instead of try/catch, then you should.

提交回复
热议问题