名称验证的自定义例外

时间:2017-08-09 06:01:22

标签: java validation exception

我想添加一个自定义异常来验证namename应该只接受[a-zA-Z]。如果名称无效,则用户需要再次输入。帮我实现这个。

public class EmployeeInfo {
static int next_id = 0;
int id;
static String name;
Date DoB, DoJ;

public void setName(final String name) {
    this.id = ++EmployeeInfo1.next_id;
    this.name = name;
}

public void setDateOfBirth(final Date DoB) {
    this.DoB = DoB;
}

public void setDateOfJoining(final Date DoJ) {
    this.DoJ = DoJ;
}

void print() {
    System.out.println("User ID: " + id);
    System.out.println("Name: " + name);
    System.out.println("Date Of Birth: " + DoB);
    System.out.println("Date of Joining: " + DoJ);
}

public static Date checkDate(final String dt) throws ParseException {

    final SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy");
    final SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy");
    final SimpleDateFormat sdf3 = new SimpleDateFormat("dd MMMM yyyy");

    Date date = null;

    try {
        date = (Date) sdf1.parse(dt);
    } catch (final ParseException e) {

        try {
            date = (Date) sdf2.parse(dt);
        } catch (final ParseException e1) {

            try {
                date = (Date) sdf3.parse(dt);
            } catch (final ParseException e2) {

                final String invalid = "Invalid Date Format,Re-enter!";
                System.out.println(invalid);
            }
        }
    }
    return date;
}




public static void main(final String[] args) throws ParseException {
    final Scanner scanner = new Scanner(System.in);
    final EmployeeInfo1 e = new EmployeeInfo1();
    System.out.println("Enter the name: ");
    e.setName(scanner.nextLine());
    Date d = null;
    while (d == null) {
        System.out.println("Enter the Date Of Birth: ");
        d = checkDate(scanner.nextLine());
    }
    e.setDateOfBirth(d);
    d = null;
    while (d == null) {
        System.out.println("Enter the Date of Joining: ");
        d = checkDate(scanner.nextLine());
    }
    e.setDateOfJoining(d);

    e.print();

}

}

4 个答案:

答案 0 :(得分:1)

您可以通过创建类extends Exception class

来定义自己的异常
class MyCustomException extends Exception
{
  public MyCustomException(String message)
  {
    super(message);
  }
}
public void setName(final String name) throws MyCustomException {
    Pattern r = Pattern.compile("[a-zA-Z]+");
    Matcher m = r.matcher(line);
    if(!m.find())
        throw new MyCustomException("Name Not Valid");

    this.id = ++EmployeeInfo1.next_id;
    this.name = name;
}

答案 1 :(得分:0)

您可以尝试使用org.apache.common.lang.StringUtils类进行验证:

{{1}}

答案 2 :(得分:0)

您可以参考此链接了解如何创建自定义异常类

How to create a custom exception type in Java?

答案 3 :(得分:0)

您可以创建自己的自定义异常类并扩展“Exception”类。 Refer this link for more details on creating custom exception