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 trialJennifer Bird
4,287 PointsPart 1 of Exception challenge . Did anyone find the answer? How do I throw and Illegal Exception on drive?
I took a 2 day pause before doing this code now I got really confused... Do I write a code on drive method that is something like "if (mBarsCount = isBattery Empty) { throw new IllegalArgumentException ("not enough battery?") ?
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;
}
}
public void charge() {
while (!isFullyCharged()) {
mBarsCount++;
}
}
public boolean isBatteryEmpty() {
return mBarsCount == 0;
}
public boolean isFullyCharged() {
return mBarsCount == MAX_BARS;
}
}
2 Answers
Steve Hunter
57,712 PointsHi Jennifer,
You're on the right lines, yes. You test the outcome, throwing an exception if the condition is met. It could look something like the below, but there are other solutions that work just as well:
public void drive(int laps) {
// Other driving code omitted for clarity purposes
if(mBarsCount - laps < 0) {
throw new IllegalArgumentException("Not enough battery remains");
} else {
mBarsCount -= laps;
}
}
I hope that helps.
Steve.
Jennifer Bird
4,287 PointsHey that helped a lot. Thanks!
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsFor example, a neater test could be:
Terence Evans
1,870 PointsTerence Evans
1,870 PointsWhen I compile this I get " unreachable statement mBarsCount -= laps; ^ Everything I've entered appears to be correct and as shown. mBarsCount was initialized in the 4th line. Ie. "private int mBarsCount;" Any idea why I'm getting this compiler message?
Steve Hunter
57,712 PointsSteve Hunter
57,712 PointsHi Terence,
Can you paste your code in here, please? We should be able to get it fixed quickly.
Steve.