Shopping Cart – Part 9
The goal of Part 9 is to bulletproof the application. A "bulletproof" application
-
Is free of bugs (behaves like we want it to).
-
Doesn't fail/crash no matter what.
Exception Handling
Exception Handling involves:
-
Catching checked exceptions (outside the application's control).
-
Fixing unchecked exceptions (resulting from badly written code).
You already caught the checked exceptions. Now, you will fix unchecked exceptions.
nextLine()
Trap
If you haven't done it already, I recommend adding a throwaway nextLine()
after each nextInt()
. The throwaways will get consumed anyway, but they will prevent bugs that may arise from the nextLine()
trap.
Task 1 – IllegalArgumentException
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
The name
and price
arguments feed from the products.txt
file. products.txt
defines the data correctly so there's nothing to worry about.
Task 2 – InputMismatchException
Thrown by
Scanner
if the user enters a value that it wasn't expecting.
If the user enters the wrong input, the application will crash.
Solution: restart the
while
loop if the user enters a row/column that isn't an int
.
Task 3 – ArrayIndexOutOfBoundsException
Thrown if you index outside the bounds of the array.
If the user enters an index that's out of range, the application will crash.
Solution: restart the while
loop if the user enters a row that isn't between 0 – 6, and a column that isn't between 0 – 2.
Task 4 – IllegalStateException
Thrown if a method is called at a bad time
The application crashes if the user tries to check out an empty cart.
Solution: If they do, restart the while
loop.
Task 5 – IllegalStateException
Thrown if a method is called at a bad time
The application throws another IllegalStateException
if the user tries to remove items from an empty cart.
Solution: If they do, restart the while
loop.