yohhoyの日記

技術的メモをしていきたい日記

throw null;(Java編)

プログラミング言語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 throw statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the throw completes abruptly for that reason. If evaluation of the Expression completes normally, producing a non-null value V, then the throw statement completes abruptly, the reason being a throw with value V. If evaluation of the Expression completes normally, producing a null value, then an instance V' of class NullPointerException is created and thrown instead of null. (snip)

CHAPTER 14 Blocks and Statements, 14.18 The throw Statement

関連URL