0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

マンガで分かる Java入門講座を読んで

Posted at

強制的にエラーを発生

throw new Exception();

new Exception()で新しく例外を発生させて
throwsに送っている

throwsによる例外の丸投げ

void method() throws ExceptionA, ExceptionB {
    処理1
    throw new ExceptionA();
    処理2
    throw new ExceptionB();
}

メソッドの引数の後ろに「throws」を書き、
処理で例外クラスを呼び出すことで、
例外をメソッド内で処理せず、
呼び出し元に丸投げすることができる。

エラーの詳細やどのメソッドの何行目で
エラーが起きたのかを出力

package sample;

public class Sample {
    public static void main(String[] args) {
        try {
            MethodA(); //例外がthrowされる可能性のある処理
        } catch (Exception e) { //eは変数
            e.printStackTrace(); //例外が起きた時の処理
        }             //(ここでは例外情報を出力)
    }

    public static void MethodA() throws Exception {
        throw new Exception();
    }
}

例外が起きても起きなくても必須な処理

try {
    例外がthrowされる可能性のある処理
} catch (受け取るException系クラス 変数) {
    例外が起きた時の処理
} finaly {
    例外が起きた場合も起きなかった場合も
    最終的にここを通る
}

複数の例外をcatch

try {
    method();    // throws ExceptionA, ExceptionB
} catch (ExceptionA eA) {
    例外Aが起きた時の処理
} catch (ExceptionB eB) {
    例外Bが起きた時の処理
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?