English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

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;
         }
            String msg = "Improper name (Should contain only characters between a to z (all small))";
            NotProperNameException exName = new NotProperNameException(msg);
            throw exName;
         }
      }
         e.printStackTrace();
      }
         e.printStackTrace();
      }
      this.name = name;
      this.age = age;
   }
   public void display() {
      System.out.println("Student's Name: ");+this.name );
      System.out.println("Student's Age: ");+this.age );
   }
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("사람의 이름을 입력하세요: ");
      String name = sc.next();
      System.out.println("사람의 연령을 입력하세요: ");
      int age = sc.nextInt();
      CustomException obj = new CustomException(name, age);
      obj.display();
   }
}

출력 결과

사람의 이름을 입력하세요:
크리쉬나
사람의 연령을 입력하세요:
136
학생의 이름: 크리쉬나
학생의 연령대: 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)
출력2:
사람의 이름을 입력하세요:
!23크리쉬나
사람의 연령을 입력하세요:
24
학생의 이름: !23크리쉬나
july_set3.NotProperNameException: Improper name (Should contain only characters between a to z (all small))
학생의 연령대: 24
at july_set3.CustomException<init>(CustomException.java:35)
at july_set3.CustomException.main(CustomException.java:56)
당신이 좋아할 만한 것