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

Abhishek Gangadhar
Abhishek Gangadhar
9,467 Points

Error in my code - IllegalArgumentException

The error says that i should implement the code before it changes the value.. But aren't we suppose to check it after the change so the if the mBarsCount variable is less than 0 we can throw an Exception

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;
    if(mBarsCount<0){
      throw new IllegalArgumentException("Too less Bars");
    }
  }

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

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

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

}

1 Answer

Yes, that's right - I've answered in your other post - but here, you try to call the method with the number of units you want to use. If that attempt fails, it'll throw the exception, else the code will continue.

Have a look at your other post - it'll make more sense there.

Steve.

Abhishek Gangadhar
Abhishek Gangadhar
9,467 Points

Well that makes sense. But i got through the code challenge with this code...

public void drive(int laps) {
    // Other driving code omitted for clarity purposes
    int num = mBarsCount - laps;
    if(num<0){
      throw new IllegalArgumentException("Too less Bars");
    }
  }

isn't the value of num and nBarsCount same with the following statement for mBarsCount

mBarCount-=laps;

Hi,

Yep - that code does the job just fine as far as it'll throw an exception if the number of laps is greater than the number of bars.

You'll need to add an else clause to your if to actually make the deuction if the test has determined that there are enough bars. Your suggested code would work fine for that too, yes. (as long as you change it to mBarsCount not mBarCount)

Steve.