Java Java Objects Harnessing the Power of Objects Throwing Exceptions

Kwabena Ayim-Aboagye
Kwabena Ayim-Aboagye
1,324 Points

Placing an illegal argument exception

I'm confused as to how to add an illegal argument exception to my drive method so that a user cannot drive more laps than there are bars of battery (barCount).
class GoKart {
  public static final int MAX_BARS = 8;
  private String color;
  private int barCount;
  private int lapsDriven;

  public GoKart(String color) {
    this.color = color;

  public String getColor() {
    return color;
  public void charge() {
    barCount = MAX_BARS;

  public boolean isBatteryEmpty() {
    return barCount == 0;

  public boolean isFullyCharged() {
    return MAX_BARS == barCount;

  public void drive() {

  public void drive(int laps) {
        lapsDriven += laps;
        barCount -= laps;

1 Answer

Think of Laps being greater than barcount, how would you do this comparison? Based on the outcome of the comparison, you will have to throw the exception which would be - throw new IllegalArgumentException("<<Exception Message>>");