Java 例 - カスタム例外

Java 实例Java 例

以下の例では、Exception を継承してカスタム例外を実装する方法を示しています:

TestInput.java ファイル

class WrongInputException extends Exception { //カスタムクラス WrongInputException(String s) { super(s); } } class Input { void method() throws WrongInputException { throw new WrongInputException("Wrong input"); //カスタムクラスをスローする } } class TestInput { public static void main(String[] args){ try { new Input().method(); } catch(WrongInputException wie) { System.out.println(wie.getMessage()); } } }

上記のコードを実行した出力結果は次のとおりです:

Wrong input

Java 实例Java 例

その他の拡張