プログラミング言語Javaのthrow文に関するちょっとしたメモ。下記コードはコンパイルエラーとはならず、実際にはjava.lang.NullPointerException
オブジェクトが送出される。
throw null; // throw new NullPointerException();と等価
The Java Language Specification(3rd Ed.), CHAPTER 14 Blocks and Statements より該当箇所を引用(下線部は強調)。
ThrowStatement:
throw
Expression;
(snip)
A
CHAPTER 14 Blocks and Statements, 14.18 The throw Statementthrow
statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then thethrow
completes abruptly for that reason. If evaluation of the Expression completes normally, producing a non-null
value V, then thethrow
statement completes abruptly, the reason being athrow
with value V. If evaluation of the Expression completes normally, producing anull
value, then an instance V' of classNullPointerException
is created and thrown instead ofnull
. (snip)
関連URL