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 (Retired) Harnessing the Power of Objects Throwing Exceptions

Halp! I can't seem to solve this!

I'm sure i'm close but I don't get this: Okay, so let's throw an IllegalArgumentException from the drive method if the requested number of laps cannot be completed on the current battery level. Make the exception message "Not enough battery remains".

GoKart.java
public class GoKart {
  public static final int MAX_BARS = 8;
  private String mColor;
  private int mBarsCount;

  public GoKart(String color) {
    mColor = color;
    mBarsCount = 0;
  }

  public String getColor() {
    return mColor;
  }

  public void drive() {
    drive(1);

  }

  public void drive(int laps) {
    // Other driving code omitted for clarity purposes
    mBarsCount -= laps;  
    try{
      mBarsCount < laps;
  System.out.println("This will never happen");
      } catch(IllegalArgumentException iae) {
       System.out.println("Not enough battery remains");
              System.out.printf("The error was: %s\n", iae.getMessage());

      }
  }

  public void charge() {
    while (!isFullyCharged()) {
      mBarsCount++;
    }
  }

  public boolean isBatteryEmpty() {
    return mBarsCount == 0;
  }

  public boolean isFullyCharged() {
    return mBarsCount == MAX_BARS;
  }

}

1 Answer

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

Make sure you check community answers before you, by clicking on "Throwing Exception" above the title of your question at the top of the page:

Java -> Java Objects -> Harnessing the Power of Objects -> Throwing Exceptions

That will lead you to community answers, asked about this challenge.

Here is direct link, just in case:

https://teamtreehouse.com/community/code-challenge:5912

There you will find a lot of helpful ones.

Check this one for example

https://teamtreehouse.com/community/exceptions-getting-an-error

It has a nice hint how to proceed.

About your code, I can just say one thing:

You have to THROW exception, and not CATCH it with try ...catch block ...