LoginSignup
2
1

More than 1 year has passed since last update.

Java SE11 Gold 対策メモ --例外処理編

Last updated at Posted at 2021-06-29

概要

  • Java SE11 Gold 試験用にまとめていた自分用メモ
  • こちらの記事を参考にSE8⇒SE11の変更点等をまとめていきます。

例外クラス

例外クラスはchecked例外uncheked例外の2種類に分類される。

checked例外

  • Java実行環境以外の環境が原因で発生する例外
  • 例外処理の実装は必須
  • Exceptionのサブクラス

unchecked例外

  • Java実行環境内が原因で発生する例外
  • 例外処理の実装は任意
  • RuntimeExceptionのサブクラス
    ※RuntimeExceptionはExceptionクラスのサブクラスであるがunchecked例外として扱う
クラス名 例外 リファレンスリンク
Errorクラスおよびそのサブクラス unchecked例外 Error
RuntimeExceptionクラスおよびそのサブクラス unchecked例外 RuntimeException
Exceptionクラスおよびそのサブクラス checked例外 Exception
java
public class Sample {
    static void methodA() throws RuntimeException {
        //static void methodA() {   // unchecked例外なのでこちらでも可能
        throw new RuntimeException();
    }
    static void methodB() throws IOException {
        //static void methodB() { // checked例外なので必須、コンパイルエラー
        throw new IOException();
    }
    public static void main(String[] args) {
        try {
            methodA();
            methodB();
        } catch(RuntimeException | IOException e) {
            System.out.println(e);
        }
    }
}

実行結果
java.lang.RuntimeException

multi-catch

  • catch(){}catch(){}catch(){}...を一命令にまとめることができる
  • catch(IOException | RuntimeException | MyException e)| を用いて列記する
  • 継承関係のある例外クラスは列記できない
  • キャッチした参照変数は暗黙的にfinalとなる
java
public class Sample {

    static void methodA() throws IOException {    //checked例外はスローが必須なので記述
        throw new IOException();
    }

    public static void main(String[] args) {
        try {
            methodA();
        } 
        //catch(Exception | IOException e){    //継承関係のある例外を列記している為コンパイルエラー
        catch(RuntimeException | IOException e) {
            //e = null;    //、暗黙的にfinalな参照変数に代入しようとしている為コンパイルエラー
            System.out.println(e);
        }
    }
}

try-with-resources

  • try文のスコープから外れるとき、変数のclose()メソッドを呼び出す
  • ;セミコロンで複数宣言可能
  • AutoCloseableまたはCloseableインターフェースを継承している必要がある
  • ここで宣言した変数は暗黙的にfinalになる
java
class MyResource implements AutoCloseable {
    private String msg;
    public MyResource(String msg) { this.msg = msg; }
    public void close() throws Exception {
        System.out.println("close() : "+ msg);
    }
}

public class Sample {
    public static void main(String[] args) {
        try (MyResource obj1 = new MyResource("obj1");
                MyResource obj2 = new MyResource("obj2")) {
            //obj1 = null;    //暗黙的finalな為、コンパイルエラー
            System.out.println("try ブロック内の処理");
            throw new SQLException();
        } catch (SQLException e) {
            System.out.println("catch ブロック:SQLException");
        } catch (Exception e) {
            System.out.println("catch ブロック:Exception");
        } finally {
            System.out.println("finally ブロック");
        }
    }
}

実行結果
try ブロック内の処理
close() : obj2
close() : obj1
catch ブロック:SQLException
finally ブロック

close()中のエラー

try-with-resources文には「抑制された例外」という
概念があります。
これをサポートするのがThrowableクラスです。

Throwable

java
class MyResource implements AutoCloseable {
    private String msg;
    public MyResource(String msg) { this.msg = msg; }
    public void method() throws SQLException {
        throw new SQLException("method() でのエラー");
    }
    public void close() throws SQLException {
        System.out.println("close() : "+ msg);
        throw new SQLException("close() でのエラー : " + msg);
    }
}
public class Sample4 {
    public static void main(String[] args) {
        try (MyResource obj1 = new MyResource("obj1");
                MyResource obj2 = new MyResource("obj2")) {
            obj1.method();
        } catch (SQLException e) {
            System.out.println("e "+ e.getMessage());
            Throwable[] errAry = e.getSuppressed();
            System.out.println("抑制例外数 : " + errAry.length);
            for(Throwable ex : errAry){
                System.out.println("ex " + ex.getMessage());
            }
        } finally {
            System.out.println("finally ブロック");
        }
    }
}
実行結果
close() : obj2
close() : obj1
e method() でのエラー
抑制例外数 : 2
ex close() でのエラー : obj2
ex close() でのエラー : obj1
finally ブロック

AssertionError

  • プログラムにバグを残さないための手法一つ
  • エンドユーザの入力チェックなどには用いない
  • 事前条件が定まっているプログラムに使用する
  • -ea(enable assertion)で有効
  • -da(disable assetion)で無効--default
java
class Test {
    private int check(int point) {
        assert (point > 0) : point + " メッセージをつけることができる";
        //assert point > 0; // ok
        //assert(point > 0); // ok
        return point * 100;
    }
    int method(int point) {
        return check(point);
    }
}
public class Sample {
    public static void main(String[] args) {
        System.out.println(new Test().method(-1));
    }
}

java Sample

実行結果
-100

java -ea Sample

実行結果
Exception in thread "main" java.lang.AssertionError: -1

参考書

オラクル認定資格教科書 Javaプログラマ Gold SE11
徹底攻略Java SE 8 Gold問題集

2
1
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
2
1