Reputation: 134
I'm new to Java and my problem here is a Simple Age Calculator. Here is my Code:
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;
}
In main,
try {
System.out.println(c.findAge("08-09-1015"));
} catch (InvalidDateFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now, this is throwing a ParseException every time i pass a String in the wrong Format. Is there any way in which I can make it throw an InvalidDateFormatException Exception instead?
Also, please leave a comment on the style and quality of my Code, provided I'm following the correct coding standards and adhering to best practices.
Upvotes: 1
Views: 3679
Reputation: 137084
To answer your prime question, you need to throw the custom exception in the catch
block:
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: " + birthDate);
}
Regarding your code, I have a couple of suggestions:
new GregorianCalendar()
and prefer Calendar.getInstance()
.findAge
method to parse the birth date.Upvotes: 3
Reputation: 22422
Define Custom Exception class for InvalidDateFormatException as below:
public class InvalidDateFormatException extends RuntimeException {
private String errorMessage;
public InvalidDateFormatException(String errorMessage, Exception exe) {
super(errorMessage);
exe.printStackTrace();
}
}
Modify your catch block to throw the exception as below :
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;
}
}
Also, I would suggest you go through the below site: https://docs.oracle.com/javase/tutorial/essential/exceptions/creating.html
Upvotes: 1