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 trialCarlos Salcedo
1,788 Pointstrouble calling the exception
i think i might be doing it wrong by the way i constructed the method in the first place and by the way i am going about of throwing the exception.
class GoKart {
public static final int MAX_BARS = 8;
private String color;
private int barCount;
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) {
lapsDriven += laps;
barCount -= laps;
try{
GoKart.drive(400);
}catch (IllegalArgumentException iae){
System.out.printf("the error was %s ", iae.getMessage());
}
}
}
Carlos Salcedo
1,788 Pointsim getting this error-... Bummer! Make sure you throw a new IllegalArgumentException if the requested amount of laps would make the battery less than zero.
1 Answer
Alexander La Bianca
15,959 PointsCarlos, See below how you should implement this method. What you did in your code is considered handling the exception, but you need a method that throws an exception before you can handle it. Also see how you can you try catch blocks to then call the public drive method.
public void drive(int laps) throws IllegalArgumentException {
if(barCount < laps) {
throw new IllegalArgumentException();
}
lapsDriven += laps;
barCount -= laps;
}
//Lets instantiate a GoKart object
GoKart someKart = new GoKart("Red");
//Lets try to drive it around laps
try {
someKart.drive(10); //Drive 10 laps
}
catch(IllegalArgumentException exc) { //This exception is raised if the kart has less than 10 bars
System.println(exc.getMessage());
}
Keep in mind that in java, a method that throws an exception like the drive method NEEDS to be handled at some point when it is called
Carlos Salcedo
1,788 Pointsexactly what i needed thanks alot for the tip
Chris Tvedt
3,795 PointsChris Tvedt
3,795 PointsWhat errors are you getting?