Is it good to catch a more general type of Exception?

后端 未结 10 1711
無奈伤痛
無奈伤痛 2021-01-06 01:22

If we are to catch specific forms of IOException, or any other kind as a matter of fact, and we only try and catch a couple (and define definitive outputs for t

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

    It depends if a more specific Exception will aid in the trouble shooting. Sometimes, like with JMX, its good to just catch the parent exception to avoid a long list of possible child exception. At least Java 7 will allow us to have more that one exception per catch. That will clean up the code quite a bit.

    0 讨论(0)
  • 2021-01-06 02:17

    The higher the exception hierarchy you're catching, and not handling them properly, or rethrowing, the more problems you will put under the carpet. You can have silent bugs that are hard to track.

    So catch only appropriate Exceptions, and let the others pass. In the top level, you can have a catch all if you don't want to crash your program, but at least log it. Still this is questionable approach, because your application could be in inconsistent state, and you can do damage to your data.

    But to answer directly to your question, IOException might be at the appropriate level. It could be enough to know for you that whatever the problem was, it related to IO, and you can act according to it. It's hard to say without more information.

    0 讨论(0)
  • 2021-01-06 02:19

    If in doubt, always catch the more specific exception!

    0 讨论(0)
  • 2021-01-06 02:20

    Generally, you only want to catch and handle exceptions you can do something with at a low level. Then at a higher level, catch any unhandled exceptions system wide, so you can record errors that occurred.

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