Should methods that throw RuntimeException indicate it in method signature?

后端 未结 7 1713
小鲜肉
小鲜肉 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:03

    From the Oracle Java tutorial:

    "If it's so good to document a method's API, including the exceptions it can throw, why not specify runtime exceptions too?" Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

    Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity.

提交回复
热议问题