Need authoritative source for why you shouldn't throw or catch java.lang.Exception

后端 未结 9 1104
无人及你
无人及你 2020-12-19 09:27

I\'ve got a coding standards meeting in just over an hour and I need a quick answer to this one.

Common wisdom among experienced Java programmers is that you don\'t

9条回答
  •  感动是毒
    2020-12-19 09:58

    I guess the point is that if you don't know how to handle a specific exception then you shouldn't catch it. It should propagate to a higher level in the hopes that it might know what to do with it. Catching exceptions too early leads to exceptions being swallowed silently and makes it impossible to do anything useful with them beyond logging.

    Imagine what would happen if FileInputStream's constructor were to log an exception internally if you tried opening a file that did not exist, but didn't indicate this failure to your code. It's fine that the error gets logged but your code would like to catch this exception and do something useful with it (such as prompting the user for a new filename). If they were to catch (Exception) you wouldn't be able to do this.

提交回复
热议问题