如何在 java 中的自定義異常中新增條件?


在建構函式或任何方法中讀取使用者的值時,可以使用 if 條件驗證這些值。

示例

在以下 Java 示例中,我們定義兩個自定義異常類,驗證姓名和年齡。

import java.util.Scanner;
class NotProperAgeException extends Throwable{
   NotProperAgeException(String msg){
      super(msg);
   }
}
class NotProperNameException extends Throwable{
   NotProperNameException(String msg){
      super(msg);
   }
}
public class CustomException{
   private String name;
   private int age;
   public static boolean containsAlphabet(String name) {
      for (int i = 0; i < name.length(); i++) {
         char ch = name.charAt(i);
         if (!(ch >= 'a' && ch <= 'z')) {
            return false;
         }
      }
      return true;
   }
   public CustomException(String name, int age){
      try {
         if (age<0||age>125) {
            String msg = "Improper age (not between 0 to 125)";
            NotProperAgeException exAge = new NotProperAgeException(msg);
            throw exAge;
         }else if(!containsAlphabet(name)&&name!=null) {
            String msg = "Improper name (Should contain only characters between a to z (all small))";
            NotProperNameException exName = new NotProperNameException(msg);
            throw exName;
         }
      }catch(NotProperAgeException e) {
         e.printStackTrace();
      }catch(NotProperNameException e) {
         e.printStackTrace();
      }
      this.name = name;
      this.age = age;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      Scanner sc= new Scanner(System.in);
      System.out.println("Enter the name of the person: ");
      String name = sc.next();
      System.out.println("Enter the age of the person: ");
      int age = sc.nextInt();
      CustomException obj = new CustomException(name, age);
      obj.display();
   }
}

輸出

Enter the name of the person:
Krishna
Enter the age of the person:
136
Name of the Student: Krishna
Age of the Student: 136
july_set3.NotProperAgeException: Improper age (not between 0 to 125)
at july_set3.CustomException.<init>(CustomException.java:31)
at july_set3.CustomException.main(CustomException.java:56)

Output2:
Enter the name of the person:
!23Krishna
Enter the age of the person:
24
Name of the Student: !23Krishna
july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))
Age of the Student: 24
at july_set3.CustomException<init>(CustomException.java:35)
at july_set3.CustomException.main(CustomException.java:56)

更新於:06-Aug-2019

638 檢視

開啟您的 職業生涯

完成課程後獲得認證

開始
廣告