Java Bootcamp – Workbooks and Challenges
)}

Shopping Cart – Part 5

Goal: Quality control the Cart class.

Unchecked exceptions

An unchecked exception crashes the app as a result of badly written code.

You should throw an:

  • IllegalArgumentException when the caller passes faulty arguments into a method/constructor.

  • IllegalStateException when an object calls its method at a "bad time" (object not in a legal state).

Throwing an unchecked exception forces the caller to improve their code.

Task 1 – Inspecting the Cart class


  1. The constructor doesn't receive any parameters so there's nothing to check.

  2. Should the setItem setter check for a null? No.

    • The code would already throw a NullPointerException. So, throwing an IllegalArgumentException would be redundant.
  3. Should the add method check for a null? No.

    • For the same reason as before.
  4. Should the remove method check for a null? No.

    • For the same reason as before.
  5. Is there a need to throw an IllegalStateException anywhere? Yes, in two places.

  • If the items ArrayList is empty, the store is not in a valid state to call the remove method.

  • If the items ArrayList is empty, the store is not in a valid state to call the checkout method.

That's all!

You added checkpoints to the Cart class. The checkpoints forbid the caller from misusing the remove and checkout methods.

Feedback Summary
4.8
39 students
5

92%
4

3%
3

0%
2

0%
1

5%
Written Reviews
There are no written reviews yet.