Java Java Objects Harnessing the Power of Objects Handling Exceptions

Leo Marco Corpuz
Leo Marco Corpuz
18,975 Points

Can't figure out my try catch syntax error

When looking at the preview, an error arrow points to the closing parenthesis of catch.

Example.java
class Example {

  public static void main(String[] args) {
    GoKart kart = new GoKart("purple");
    if (kart.isBatteryEmpty()) {
      System.out.println("The battery is empty");
    }
    kart.drive(42);
    try {
     kart.drive(42);
    }
    catch (IllegalArgumentException) {
    System.out.println("Not enough battery to drive");
    }
  }

}
GoKart.java
class GoKart {
  public static final int MAX_BARS = 8;
  private int barCount;
  private String color;
  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() {
    drive(1);
  }

  public void drive(int laps) {
    if (laps > barCount) {
      throw new IllegalArgumentException("Not enough battery remains");
    }
    lapsDriven += laps;
    barCount -= laps;
  }

}

1 Answer

Brendan Whiting
MOD
Brendan Whiting
Front End Web Development Treehouse Moderator 84,129 Points

You need to give the exception a name in Java as opposed to other languages. And when you crab the exception that was thrown into a named variable, you can then use that variable in your catch block. When the exception is thrown from GoKart.java, it already has a message, so you can just pass a long the same message in your catch block rather than creating your own.

Also, you've put kart.drive(42) in two places, one of those inside a try block, and one outside. So the one outside is going to cause problems.