Java Java Objects Harnessing the Power of Objects Throwing Exceptions

Kingsley Maduaka
Kingsley Maduaka
467 Points

catching exceptions. how do i place the variables or method in exception cases.

i tried different ways of placing the argument exceptions . really confused on how to put put the variables to avoid syntax error .

GoKart.java
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() {

    try{
      drive(1);


    }catch(IllegalArgumentException iae){

      System.out.println("wrong");
  }

  public void drive(int laps) {
    try{ 
      lapsDriven += laps;
      if (laps < 0);
      barCount -= laps;

    }catch(IllegalArgumentException iae){
      if (barCount < 1);

      System.out.println("wrong");
    }   

  }
}

1 Answer

Steven Parker
Steven Parker
177,726 Points

Here's a few hints:

  • you only need to modify the version of "drive" that takes an argument (the other one calls it)
  • your test expression will need to compare the "laps" with the "barCount"
  • you only need to "throw" the exception, you won't need a "try" or "catch"
  • leave the original code to do what it normally does if no exception is thrown
  • you won't need to print anything

Give it a shot with that in mind, and write again if you still have trouble.