Throwing Unchecked Exceptions
Learning Objectives Covered
By the end of this lesson, you will be able to throw an unchecked exception to alert the user when input is invalid.
Learning Materials
Time Commitment
Approximately 35-45 minutes
Read (Approximately 20-25 minutes)
Try (Approximately 15-20 minutes)
Shoddy Practices High School is trying to calculate final grades for students. Unfortunately, all the grades are handwritten and in big piles of paper. We need to create a program that lets people type in the grades that a particular student achieved in a year, exclude the smallest grade, then return the average of the rest of the grades. Since people will be typing in these grades manually, they make mistakes! We need to make sure each subject’s grade is greater than or equal to 0.0 and less than or equal to 4.0. We also assume that students have taken at least 2 subjects during the year.
Please download the GradeCalculator
code from here: ThrowingExceptions.zip
How to run the code
You can run the code in BlueJ by…
- instantiating the
GradeCalculator
class, - running the
gradeEntryForStudent
method, - specifying the number of subjects,
- entering one grade per subject in the terminal window.
After instantiating the GradeCalculator
class, you run the gradeEntryForStudent
method. You will then see a window asking you for the value for int numberOfSubjects
for the method:
- This is where you pass in the number of subjects as a method argument.
After providing the number of subjects you can enter in grades in the Terminal window:
- First, type in grades, then press enter; the prompt for the next grades appear.
Goal
We need to make sure we protect our assumptions and not let people calling us make mistakes. What would you change in the code?
Test cases
-
Input: 5 subjects, each with grades [1, 2, 3, 4, 4]
Output: Final grade for this student: 3.25 -
Input: 2 subjects, each with grades [1, 2]
Output: Final grade for this student: 2.00 -
Input: 1 subject, with a grade of 4
Output:IllegalArgumentException
thrown because there must be at least two subjects worth of grades -
Input: 2 subjects, each with grades [4, 5]
Output:IllegalArgumentException
thrown because the grade at index 1 is not a valid grade