Throwing generic Exception discouraged?

前端 未结 5 528
面向向阳花
面向向阳花 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:24

    If you throw more specific exceptions, that does not stop any calling code from dealing with all of them in one Exception catch block. Being more specific is more documenting as to what type of errors occur, making it easier for programmers to deal with them separately.

    Additionally, by throwing "Exception" itself you're basically telling callers of your code that they can't rule out any class of exception. An IOException might occur, as might a NumberFormatException, etc.

提交回复
热议问题