How many statements in a try/catch statement?

前端 未结 13 1248
予麋鹿
予麋鹿 2021-01-12 12:42

Should I put multiple statements in a try and then catch all possible exceptions, or should I put only one statement in the try statement?

Example:



        
相关标签:
13条回答
  • 2021-01-12 13:10

    The first choice, it allows more understandable and readable code, more so your procedure or function should be trying to do a very specific action, the fact that you have 2 separate calls that might throw 2 separate exceptions means its doing more than it supposed to, maybe this is necessary

    Either spit the 2 calls into 2 separate methods or go with the first approach.

    The only reason you might want to go with the second approach is if your method does 2 actions and a little bit more, but you only want to handle 2 lines of code for exceptions, and maybe wrap them and continue executing but this isn't advised

    0 讨论(0)
  • 2021-01-12 13:11

    Normally you can separate what you are trying to do into a specific task. Put the code related to that task into one try catch and then if something goes wrong you know that task has failed and you can try to recover from there.

    i find this method reduces the amount of catch code you need to write and keeps related logic together.

    0 讨论(0)
  • 2021-01-12 13:13

    I would prefer using multiple statements in a try block and then catch all possible exceptions. Not sure why but I always do that while coding

    0 讨论(0)
  • 2021-01-12 13:14

    If they are truly separate like that, then the first is better practice, simply because it's shorter.

    However, if it's possible for MaybeThrowIOException() to throw a FooBarException, or for MaybeThrowFooBarException() to throw a IOException, then you should only wrap them together if you want them both to take the same action upon an exception!

    0 讨论(0)
  • 2021-01-12 13:15

    you can use any of them.

    but if using the first then you should catch the more specific exceptions.

    0 讨论(0)
  • 2021-01-12 13:18

    I think your first example is better practice than your second.

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