カスタム例外
CoddyのJavaジャーニー「ロジックとフロー」セクションの一部 — レッスン 43/59。
独自の例外クラスを作成するには、Exception クラスを拡張します。アプリケーションで特定の種類のエラーを処理する必要がある場合に便利です。
カスタム例外を作成する方法:
public class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}これがその使い方です:
if (age < 0) {
throw new AgeException("Invalid age: " + age);
}上記のコードを age = -5 で実行すると、プログラムは以下をスローします:
AgeException: Invalid age: -5
チャレンジ
簡単EmailException という名前のカスタム例外クラスと、1つの引数を取る validateEmail という名前のメソッドを作成してください:
- 検証対象の String (
email)
このメソッドは、以下のメッセージでカスタム例外をスローするものとします:
- email が null の場合: "Email cannot be null"
- email が空の場合: "Email cannot be empty"
- email に @ が含まれない場合: "Email must contain @"
- email に @ の前にテキストが含まれない場合: "Email must have a local part"
- 検証が成功した場合: "Valid email" を返す
チートシート
Exception クラスを拡張してカスタム例外を作成します:
public class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}throw キーワードを使用してカスタム例外をスローします:
if (age < 0) {
throw new AgeException("Invalid age: " + age);
}自分で試してみよう
import java.util.Scanner;
class EmailException extends Exception {
public EmailException(String message) {
super(message);
}
}
public class Main {
public static String validateEmail(String email) throws EmailException {
// ここにコードを書いてください
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String email = scanner.nextLine();
if (email.equals("null")) {
email = null;
}
try {
System.out.println(validateEmail(email));
} catch (EmailException e) {
System.out.println(e.getMessage());
}
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。