LoginSignup
0
0

More than 3 years have passed since last update.

Java Error Handlingの基礎 - catch は一番手前でしか拾われないという話

Last updated at Posted at 2020-02-03

エラーをどこで拾うかはほんとに迷う。

subroutineの中でうかつにtry-catchしてしまうと、拾いたいところまで届かなかったりする。

javaも同じだった

届かない例

同じExceptionを多段なsubroutineでかけると、内側のsubroutineでしか拾えない。

public class MyException {
    final private static int[] M = {1,2,3}; 
    public static void main(String[] args) {
        try {
            subroutine(M);
        }
        catch ( ArrayIndexOutOfBoundsException e ) {
           System.out.println("[SECOND] catch : " + e.getMessage());
        }
    }

    public static void subroutine(int[] M) throws ArrayIndexOutOfBoundsException {
        try {
            System.out.println(M[4]);
        }
        catch ( ArrayIndexOutOfBoundsException e ) {
           System.out.println("[FIRST] catch : " + e.getMessage());
        }
    }
}

result

[FIRST] catch : Index 4 out of bounds for length 3

届く例

内側のcatchの中で再度 throw させると、外側でも拾える。
throwするときは引数 e をいい感じにして渡す。eのままだとエラーになった。よくわかってない。

public class MyException {
    final private static int[] M = {1,2,3}; 
    public static void main(String[] args) {
        try {
            subroutine(M);
        }
        catch ( ArrayIndexOutOfBoundsException e ) {
           System.out.println("[SECOND] catch : " + e.getMessage());
        }
    }

    public static void subroutine(int[] M) throws ArrayIndexOutOfBoundsException {
        try {
            System.out.println(M[4]);
        }
        catch ( ArrayIndexOutOfBoundsException e ) {
           System.out.println("[FIRST] catch : " + e.getMessage());
           throw new ArrayIndexOutOfBoundsException(e.getMessage());
        <--- throwさせる
        }
    }
}

result

[FIRST] catch : Index 4 out of bounds for length 3
[SECOND] catch : Index 4 out of bounds for length 3

というわけで、何が言いたいかというと
- errorを拾うところはできるだけまとめたほうが見やすい
- けどそれぞれのmoduleの役割もあるので、責任範囲で区切るのも大事
- 区切るときに、安易に Exception/RUntimeException を拾っちゃうと外側まで届かない
- 内側ではできるだけ細かく、ちゃんとした xxException を拾ってかないといけない
- そのためには、何をしたら何のexceptionが出るのかしっかりわかってないといけない
- if & throw するのがベストなんだろう
- ( if == 0: throw new DivededByZeroException みたいな)

reference
http://math.hws.edu/javanotes/c8/s3.html

ここの最後のコードも、 if + throw で成り立ってる。そうしよう的なことを書いてる、と思うんだが、眠すぎてもう理解できないので寝る。

まあそんな感じのメモ

0
0
4

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