我是Java新手,我的问题是简单年龄计算器。这是我的代码:
public class Client {
public int findAge(String birthDate) throws InvalidDateFormatException {
// InvalidDateFormatException is a custom defined
int age = 0;
try {
Calendar past = new GregorianCalendar();
Calendar present = Calendar.getInstance();
past.setTime(new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(birthDate));
age = present.get(Calendar.YEAR) - past.get(Calendar.YEAR);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (age >= 0) ? age : 0;
}
主要是
try {
System.out.println(c.findAge("08-09-1015"));
} catch (InvalidDateFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
现在,每次我以错误的格式传递String时,都会抛出 ParseException 。有什么方法可以让它抛出 InvalidDateFormatException 异常而不是?
此外,如果我遵循正确的编码标准并遵守最佳做法,请对我的准则的风格和质量发表评论。
答案 0 :(得分:1)
为InvalidDateFormatException定义自定义异常类,如下所示:
public class InvalidDateFormatException extends RuntimeException {
private String errorMessage;
public InvalidDateFormatException(String errorMessage, Exception exe) {
super(errorMessage);
exe.printStackTrace();
}
}
修改您的catch块以抛出异常,如下所示:
public class Client {
public int findAge(String birthDate) throws InvalidDateFormatException {
int age = 0;
try {
Calendar past = new GregorianCalendar();
Calendar present = Calendar.getInstance();
past.setTime(new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH).parse(birthDate));
age = present.get(Calendar.YEAR) - past.get(Calendar.YEAR);
} catch (ParseException e) {
throw new InvalidDateFormatException("Invalid Date Format while finding Age", e);
}
return (age >= 0) ? age : 0;
}
}
另外,我建议你浏览下面的网站: https://docs.oracle.com/javase/tutorial/essential/exceptions/creating.html