yohhoyの日記

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

メソッドthrows節への非検査例外指定

プログラミング言語Javaの非検査例外(unchecked exception)とthrows節の関係についてメモ。メソッドthrows節で非検査例外を指定することは可能だが、メソッド呼び出し側でのコンパイル時チェックは行われない。*1

void func() throws NullPointerException {
  //...
  throw new NullPointerException();
}
void caller() {
  // try構文/メソッドthrows宣言は不要
  func();
}

Java Language Specification, Java SE 7 Editionより一部引用。

It is permitted but not required to mention unchecked exception classes (§11.1.1) in a throws clause.

Chapter 8. Classes, 8.4.6. Method Throws

The Java programming language requires that a program contains handlers for checked exceptions which can result from execution of a method or constructor (§8.4.6, §8.8.5). (snip)

The unchecked exception classes (§11.1.1) are exempted from compile-time checking.

Chapter 11. Exceptions, 11.2. Compile-Time Checking of Exceptions

*1:java.lang.RuntimeExceptionまたはjava.lang.Errorの派生クラスはunchecked exceptionとして扱われる。