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?

【JavaGold】例外とアサーション

Last updated at Posted at 2025-01-09

例外とアサーション

マルチキャッチ

  • ExceptionとRuntimeExceptionをマルチキャッチで同時に扱うことはできない。

プログラマーが独自に作成する例外クラスは、java.lang.Exceptionクラスのサブクラスでなければならない。

マルチキャッチ実装例①
try {
    // do something
} catch (AException | BException b) {
    // do something
}
マルチキャッチ実装例②:SampleExceptionクラス
public class SampleException extends Exception {
    public SampleException(String message) {
        super(message);
    }
}
TestExceptionクラス
public class TestException extends SampleException {
    public TestException(String message) {
        super(message);
    }
}
Sampleクラス
public class Sample {
    private static void test() throws TestException {
        try {
            // do something
            throw new TestException("A");
        } catch (SampleException | RuntimeException e) {
            throw new RuntimeException("B");
        }
    }

    public static void main(String[] args) {
        try {
            test();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
実行結果
B

try-with-resources

  • try-with-resourcesの主な目的は例外処理ではない。
  • try-with-resources文で自動的に閉じられるリソースを定義することができるのは、java.io.Closeableインタフェースとjava.lang.AutoCloseableインタフェースのいずれかを実装したクラス
  • リソースはfinalもしくは実質的にfinalではなくてはならない。
構文
try (自動的に閉じるリソース宣言) {
    // リソースを使った処理
}
実装例
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class FileCopy {
    public static void main(String[] args) {
        try (BufferedReader in = new BufferedReader(new FileReader(new
                                        File("input.txt")));
                BufferedWriter out = 
                    new BufferedWriter(new FileWriter(new
                        File("result.txt")));) {

            String line = null;
            // データをコピーする
            while ((line = in.readLine()) != null) {
                out.append(line);
                out.newLine();
            }
            out.flush();
        } catch (IOException e) {
            throw new RUntimeException(e);
        }
    }
}
  • try-with-resourcesを使って記述するとリソースが自動的に閉じるのに伴い、finallyブロックが必要なくなった。
  • 複数のリソースを対象とする場合は、セミコロン「;」で区切って列挙する。
  • try-with-resourcesのtryブロック内で例外が発生したとき、close、catchブロック、finallyブロックの順番で実行される。
  • AutoCloseableを実装し、closeメソッドをオーバーライドする。
実装例
public class TroubleResource implements AutoCloseable {
    @Override 
    public void close() throws Exception {
        throw new RuntimeException("trouble");
    }
}

public class TroubleMaker {
    public static void main(String[] args) {
        try (TroubleResource a = new TroubleResource()) {
            throw new Exception();
        } catch (RuntimeException e) {
            System.out.println("A");
        } catch (Exception e) {
            System.out.println("B");
        }
    }
}
実行結果
B

closeメソッドのほうでも例外が発生している場合は、try-catchができているメインのほうだけが出力される。

引数がnullでないことを確認するためのアサーション

assert param != null;

アサーションを有効にするためのコマンド

java -ea Sample
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?