本文へスキップ
BecomeCoder

Javaのエラー · エラー10

unreported exception ... must be caught or declared ― checked例外の処理漏れ(コンパイル)

Java の checked 例外(IOException など)は、投げる可能性があるコードを書いたら 必ず try-catch するか、メソッドに throws を宣言しないとコンパイルが通りません。

出るコード

void readFile() throws Exception {
}

void caller() {
    readFile();   // checked例外を処理も宣言もしていない
}

エラーメッセージ

error: unreported exception Exception; must be caught or declared to be thrown

直し方

try-catch で囲むか、呼び出し側のメソッドにも throws を付けて呼び出し元に処理を委ねます。

void caller() throws Exception {
    readFile();
}