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 trialTrung Nguyen
1,158 Pointsthrow Exception
I dont understand what is wrong with my implementation ?
public void drive(int laps) { // Other driving code omitted for clarity purposes try { if (laps > this.mBarsCount) { throw new IllegalArgumentException("Not enough battery remains"); } mBarsCount -= laps; } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } }
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
try {
if (laps > this.mBarsCount) {
throw new IllegalArgumentException("Not enough battery remains");
}
mBarsCount -= laps;
}
catch (IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
}
public void charge() {
while (!isFullyCharged()) {
mBarsCount++;
}
}
public boolean isBatteryEmpty() {
return mBarsCount == 0;
}
public boolean isFullyCharged() {
return mBarsCount == MAX_BARS;
}
}
2 Answers
Simon Coates
28,694 PointsThe following seems to work
public void drive(int laps) throws IllegalArgumentException {
if (laps > this.mBarsCount) {
throw new IllegalArgumentException("Not enough battery remains");
}
mBarsCount -= laps;
}
RAFAEL LOUSTAUNAU
1,170 PointsI don't know why the try method wont work but I did this and it passed.
public void drive (int laps) {
if (mBarsCount!=laps) throw new IllegalArgumentException("Not enough battery remains"); { mBarsCount-=laps; } }
Simon Coates
28,694 Pointsputting a throw statement inside a try block, means that the exception will be caught immediately. Sometimes, you want the code that calls your method to have to deal with the Exception.
Simon Coates
28,694 PointsSimon Coates
28,694 PointsUnless you add throws to the method, i think it forces you to use a try catch block in the method itself. The task seems to want you to throw a message and force the calling code to deal with a possible exception.