Index ¦ Archives

JavaMemo_2

Javaのエントリーポイント

public static void main
引数がStringの配列、可変長数であること

public class Main {
    public static void main(String[] args) {
        System.out.println(args.length));
    }
}
// 実行時に配列インスタンスが生成されるためlength0となる。
// argsだと、ハッシュコード
0

例外の基本形

catchは複数記述できるが、それ以外を複数記述するとコンパイルエラーとなる。
try,catch,finallyの順番も守る必要がある。

try {
    // 処理
} catch(Exception e) {
    // 例外発生時の処理
} finally {
    // 必ず実行したい処理
}

finally複数のためコンパイルエラー

try {

} catch (Exception e) {

} finally {

} finally {

}

記述の順番が不正なためコンパイルエラー

try {

} finally {

} catch(Exception e) {

}

catchの省略

try {
    System.out.println("A");
} finally {
    System.out.print("B");
}
A
B

catchを複数記述した際の、継承関係によるコンパイルエラー
スーパークラスで先に例外をcatchするため、
サブクラスのRuntimeexceptionは到達不可能コードとなる

try {
    System.out.println("A");
} catch (Exception e) {
    System.out.println(e);
    // 到達不可能コード
} catch (RuntimeException re) {
    System.out.println(re);
}

サブクラスを先に記述する

try {
    System.out.println("A");
} catch (RuntimeException re) {
    System.out.println(re);
} catch (Exception e) {
    System.out.println(e);
}
A

例外を投げる

try {
    // 例外クラスをインスタンス化して投げる。  
    throw new Exception();
    // catchする
} catch(Exception e) {
    System.out.println(e);
}
java.lang.Exception

例外を再度投げる

public class Main {
    public static void main(String[] args) {
        try {
            throwError();
            // catchする
        } catch (RuntimeException re) {
            System.out.println("catch");
            System.out.println(re);
        }
    }

    private static void throwError() {
        try {
            // 例外クラスをインスタンス化して投げる。
            throw new RuntimeException();
        } catch (RuntimeException re) {
            // 再度投げる
            throw re;
        }
    }
}
catch
java.lang.RuntimeException

© Tokus. Built using Pelican. Theme by Giulio Fidente on github.