Java Java Objects Harnessing the Power of Objects Handling Exceptions

Ephraim Smith
Ephraim Smith
11,921 Points

Handling Exceptions: code matches community answers but doesn't work.

Message: "Bummer!. Make sure you print out the error message to the console using the exception's getMessage method."

I've included the getMessage method to no avail. I know it's something simple...

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");
    }
    try {
    kart.drive(42);
    } catch (IllegalArgumentException iae) {
      System.out.println(iae.getMessage());
    }
  }

}
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");
    }
    lapsDriven += laps;
    barCount -= laps;
  }

}

2 Answers

Jennifer Nordell
STAFF
Jennifer Nordell
Treehouse Staff

Hi there! I'm of the opinion that you aren't missing anything at all. When I copy/paste your code into the challenge, it passes with flying colors! My best suggestion to you is to copy the code you've posted here, restart the challenge, paste it in and then hit check work.

Hope this helps! :sparkles:

Ephraim Smith
Ephraim Smith
11,921 Points

Hey Jenn,

Your suggestion worked! Is this a known bug with this particular Objective? Kind of frustrating to spend an hour trying to fix something that's not broken... Thanks for your help!

Jennifer Nordell
Jennifer Nordell
Treehouse Staff

ephraimsmith no, not that I'm aware of. I will say that I have seen this happen to others on different objectives throughout all topics but very sporadically. It has happened to me once or twice. I have not yet been able to identify a pattern and have been using this platform for over 2 years. My best guess would be that it has to do with some cached data somewhere, but that's just a theory. To mitigate this, I generally copy/paste my code into a text editor on my system right before I hit "Check work". It's just a security measure in case this happens. But again, it's very rare (at least in my experience).

Suhas Nukala
Suhas Nukala
2,184 Points

same thing happened to me. i tried restarting the challenge and it worked