Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Harnessing the Power of Objects Handling Exceptions

shu Chan
shu Chan
2,951 Points

Handling Exceptions: Make sure you print out the error message to the console using the exception's getMessage method.

For the life of me I can't find what is the problem to cause this, can someone tell me what's wrong with my code?

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("Whoa there cow boy, too many laps!");
      System.out.printf("The error was %S", 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 left");
    }
    lapsDriven += laps;
    barCount -= laps;
  }

}

3 Answers

shu Chan
shu Chan
2,951 Points

Resetting it did the trick. I spent 2 hours pouring through documentation to see what I did wrong but it was a bug in the exercise....

jason yu
jason yu
803 Points

System.out.printf("The error was %S", iae.getMessage());

For that line you wrote, you need a lowercase %s. You wrote it with a capital. If that doesn't work, try deleting the .getMessage() idk where this came from

This should work: System.out.printf("The error was %s", iae);

shu Chan
shu Chan
2,951 Points

I changed the s to lower case but it still won't accept the answer, when I run the preview, the code works perfectly. I'm truly at a loss here

Jason Anders
Jason Anders
Treehouse Moderator 145,860 Points

Maybe try resetting the challenge.

When I implement jason yu's corrections he provided for you, the challenge does pass. So the code is correct. Resetting the challenge should help. :)

:dizzy: