Multiple try-catch or one?

前端 未结 11 1721

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:37

    Second method. Keeping the code that might throw an exception separate from other code - keeps the section smaller and easier to manage instead of wrapping all code, even that which will not throw exceptions.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 09:46

    It depends on the nature of the type of errors happen in your code.

    1. If the handling of those errors you are going to do is same go for single try ... catch for that group of code. Else it will be too tedious.

    2. If the errors required different handling, separate it because you have to.

    DO NOT APPLY A SINGLE METHOD FOR ALL CASES. PROGRAMMING MOST OF THE TIME IS CONTEXT SPECIFIC :)

    You need to reach a balance of "GOOD/COMPLEX" and "BAD/SIMPLE". The more you code, you will be less stuck in this kind of dilemma :)

    Happy programming!

    0 讨论(0)
  • 2020-12-08 09:47

    If I could choose the second I would probably separate this into two functions.

    0 讨论(0)
  • 2020-12-08 09:48

    2nd way but ideally use code guards - try/catch can be costly, if you catch an exception.

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