Java 實(shí)例 - 自定義異常

Java 實(shí)例 Java 實(shí)例

以下實(shí)例演示了通過(guò)繼承 Exception 來(lái)實(shí)現(xiàn)自定義異常:

/*
 author by w3cschool.cc
 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());
      }
   } 
}

以上代碼運(yùn)行輸出結(jié)果為:

Wrong input

Java 實(shí)例 Java 實(shí)例