Should methods that throw RuntimeException indicate it in method signature?

后端 未结 7 1710
小鲜肉
小鲜肉 2020-11-30 23:43

For example, many methods in frameworks/JDK might throw

java.lang.SecurityException 

but this is not indicated in the method signature (si

7条回答
  •  清歌不尽
    2020-12-01 00:04

    Take a look at the javadoc for Collection#add

    There's a whole slew of unchecked exceptions mentioned:

    Throws:
    UnsupportedOperationException - add is not supported by this collection.
    ClassCastException - class of the specified element prevents it from being added to this collection.
    NullPointerException - if the specified element is null and this collection does not support null elements.
    IllegalArgumentException - some aspect of this element prevents it from being added to this collection.
    

    If you have the patience, I'd recommend thoroughly documenting the possible exceptions thrown by your methods this way. In a way, it's even more important to do this for unchecked exceptions, as checked exceptions are somewhat self-documenting (the compiler forces the calling code to acknowledge them).

提交回复
热议问题