Menu
Coddy logo textTech

カスタム例外

CoddyのJavaジャーニー「オブジェクト指向プログラミング」セクションの一部。レッスン 60/87。

Javaに組み込まれている例外は、多くの一般的なエラー状況に対応していますが、アプリケーションのドメインに固有の例外が必要になることもあります。カスタム例外を使用すると、何が問題だったのかを明確に伝える、意味のあるエラー型を作成できます。

custom exception を作成するには、既存の exception class を単純に extend します。checked exception の場合は、Exception を extend します。

public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);
    }
}

非検査例外の場合は、RuntimeExceptionを拡張します:

public class InvalidAgeException extends RuntimeException {
    public InvalidAgeException(String message) {
        super(message);
    }
}

super(message) の呼び出しはエラー message を親 class に渡し、getMessage() を通じて利用できるようにします。その後、他の exception と同じように、custom exception を throw して catch できます。

public void withdraw(double amount) throws InsufficientFundsException {
    if (amount > balance) {
        throw new InsufficientFundsException("Balance too low: " + balance);
    }
    balance -= amount;
}

// 使用例
try {
    account.withdraw(1000);
} catch (InsufficientFundsException e) {
    System.out.println(e.getMessage());
}

Custom例外を使うとコードが読みやすくなり、呼び出し元が特定のエラー条件をそれぞれ異なる方法で処理できるようになります。明確なエラーの伝達が重要なAPIやライブラリを構築する場合に、特に役立ちます。

challenge icon

チャレンジ

簡単

さまざまなエラーシナリオを処理するために custom exceptions を使用するチケット予約システムを作成しましょう!チケット予約時に何が問題だったのかを明確に伝える、意味のある exception types を作成します。

コードを4つのファイルに分けて整理します。

  • TicketSoldOutException.java: チケットが longer available である場合に使用する custom checked exception を作成します(Exception を extends)。この exception は constructor で message を受け取り、super(message) を使用して parent class に渡します。
  • InvalidSeatException.java: someone が invalid seat number を予約しようとした場合に使用する custom unchecked exception を作成します(RuntimeException を extends)。この exception も message を受け取り、parent に渡します。
  • TicketBooth.java: ticket sales を manages する class を作成します。booth では、available seats の total number と、valid な seat number の最大値を追跡します。以下を含めてください。

    available seats の total number を受け取る constructor。

    予約を検証する bookTicket(int seatNumber) method。チケットが残っていない場合(available seats が 0 以下の場合)、message "No tickets remaining" を指定して TicketSoldOutException を throw します。seat number が 1 未満、または total seats より大きい場合は、message "Seat [seatNumber] does not exist" を指定して InvalidSeatException を throw します。Otherwise、available seats を 1 減らし、Booked seat [seatNumber] successfully を print します。

    現在の available seats の count を返す getAvailableSeats() method。

  • Main.java: ticket system をまとめます!2つの入力、つまり total number of seats と予約する seat number を受け取ります。

    given total seats を使用して TicketBooth を Create します。その後、try-catch block の中で指定された seat number の予約を attempt します。TicketSoldOutException は checked なので、これを handle する must があります。最初に TicketSoldOutException を catch し、Booking failed: [exception message] を print します。次に InvalidSeatException を catch し、同じ形式の Booking failed: [exception message] を print します。

    try-catch block の After、getter method を使用して Remaining seats: [count] を print します。

入力は、total seats(integer)、seat number to book(integer)の順に2つ受け取ります。

checked exceptions は caller に try-catch または throws で handle することを強制しますが、unchecked exceptions には明示的な handling が不要である点に注目してください。エラーが caller に anticipate して recover してほしいものかどうかに基づいて、exception type を選択しましょう!

自分で試してみよう

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int totalSeats = scanner.nextInt();
        int seatNumber = scanner.nextInt();
        
        // TODO: 指定された総座席数でTicketBoothを作成する
        
        // TODO: try-catchブロックを使用して座席の予約を試みる
        // - 最初にTicketSoldOutExceptionをキャッチし、"Booking failed: [exception message]"を出力する
        // - InvalidSeatExceptionをキャッチし、"Booking failed: [exception message]"を出力する
        
        // TODO: After the try-catch, print "Remaining seats: [count]"
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

オブジェクト指向プログラミングのすべてのレッスン

自分で練習してみよう: Javaオンラインコンパイラ