1

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.

1
  • Done. I realized it now. And thank you for pointing it out because I just discovered about Meta Stack Exchange and the Roll Back feature. Commented Sep 21, 2015 at 4:40

2 Answers 2

3

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:

  • Do not use new GregorianCalendar() and prefer Calendar.getInstance().
  • The way you calculate the age is broken: you don't take into account the month and the day (let's say we are 2015-09-20, and the birth date is 2014-12-01, your code will output 1 even if the baby is not 1 year old yet).
  • Consider giving a Date argument instead of a String argument. It should not be the responsibility of the findAge method to parse the birth date.
  • If you are using Java 8, consider using the new Java Time API.
Sign up to request clarification or add additional context in comments.

2 Comments

Okay! I got it. Updated the Question with my new Code. Thanks! The Compilers we're provided are still 1.5 , So I'll stick with it for now.
Please dont update your code after youve asked the question like that. Now your code appears fine and your question relates to what was broken. Its not followable.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.