Post

Created by @nathanedwards
 at October 31st 2023, 11:24:44 pm.

AP Computer Science Exam Question - Throwing Exceptions

Question:

Write a Java method named getAge that takes an integer parameter representing a person's year of birth and returns their age. The method should throw an exception if a negative value is passed as the year of birth.

Signature:

public static int getAge(int yearOfBirth) throws IllegalArgumentException {
    // code goes here
}

Examples:

getAge(1990);    // returns: 31
getAge(2005);    // returns: 16
getAge(1985);    // returns: 36
getAge(-1990);   // throws: IllegalArgumentException

Provide your implementation for the getAge method.

Answer:

public static int getAge(int yearOfBirth) throws IllegalArgumentException {
    if (yearOfBirth < 0) {
        throw new IllegalArgumentException("Year of birth cannot be negative.");
    }
    
    int currentYear = java.time.Year.now().getValue();
    return currentYear - yearOfBirth;
}

Explanation:

The given method getAge takes an integer parameter yearOfBirth representing a person's year of birth. The method checks if the yearOfBirth parameter is negative. If it's negative, an IllegalArgumentException is thrown. Otherwise, the method proceeds to calculate the age by subtracting the yearOfBirth from the current year using the java.time.Year.now().getValue() call. Finally, the calculated age is returned.

In the implementation, we use the IllegalArgumentException exception to handle the case when a negative value is passed as the year of birth. This is a common practice in Java to throw this exception when an invalid argument is passed to a method. By including the throws IllegalArgumentException in the method signature, we inform the calling code that this method may throw this exception, and it should handle it appropriately.

The code uses the java.time.Year.now().getValue() call to obtain the current year dynamically. This ensures that the age is calculated accurately regardless of when the method is called. This call returns the current year as an integer, which is later used for the age calculation.

In the provided example, the test cases (1990, 2005, 1985) result in valid ages, so the method returns the respective age value. However, for the test case -1990, it throws an IllegalArgumentException with the message "Year of birth cannot be negative." This exception is handled by the caller accordingly.