Throwing generic Exception discouraged?

前端 未结 5 529
面向向阳花
面向向阳花 2021-01-04 04:04

Why is it discouraged to throw a generic (java.lang.Exception) exception, when it is usually sufficient to handle most conditional failures within a method? I understand tha

5条回答
  •  情话喂你
    2021-01-04 04:32

    The problem is that Exception is also the superclass of RuntimeException, which encompasses some stuff that shouldn't be caught as it indicates a problem with the programming rather than an exceptional condition that arises from context. You don't want to catch a BufferOverflowException or UnsupportedOperationException under normal circumstances. Besides, throwing separate Exception types gives the calling code control over how to handle each one. Boilerplate is reduced in Java 7 with the new multi-catch feature.

提交回复
热议问题