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 trialNicolas Murrduck
Courses Plus Student 366 PointsLooks like you didn't catch the exception.
What i am doing wrong here please somone it keeps saying that i didnt catch the exception
public class Main {
public static void main(String[] args) {
GoKart kart = new GoKart("yellow");
if (kart.isBatteryEmpty()) {
System.out.println("The battery is empty");
}
kart.drive(2);
try {
kart.drive(9);
} catch (IllegalArgumentException iae) {
System.out.printf("%s\n", iae.getMessage());
}
}
}
Aditya Puri
1,080 Pointshey!! I don't understand what went wrong in your program..I am having the same problem but when I added "kart.drive(2)" in the try statement, it resolved the problem...I don't understand how this happens.
How is kart.drive(2)
invalid argument? There are 8 energy bars. Then how can depleting 2 make a difference?
Steve Hunter
57,712 PointsHi Aditya,
The drive()
method can throw an exception. It doesn't have to throw the exception, but the possibility of the exception being thrown must always be caught.
Make sense?
Steve.
Aditya Puri
1,080 PointsSO, It won't throw the exception in this case but we are making it so that if the "2" were a "9", then it would throw an exception? We are making sure that if it checks for the error?
Steve Hunter
57,712 PointsYes. Exactly that. We would define the method as being able to throw a particualr type of exception. That exception must then be handled whether it arises or not.
Aditya Puri
1,080 Pointsoh, ok thx!!
2 Answers
Steve Hunter
57,712 PointsHi Nicolas,
The drive
method is what can throw the exception. There's no try|catch
block around the existing method call, kart.drive(2);
which is what the compiler is complaining about.
There's no need to call the method again, just build the exception handling around the code that exists:
try {
kart.drive(2);
} catch (IllegalArgumentException iae) {
System.out.printf(iae.getMessage());
}
I hope that helps.
Steve.
Nicolas Murrduck
Courses Plus Student 366 PointsYea i figured out Thanks!!! Steve Hunter
Nicolas Murrduck
Courses Plus Student 366 PointsNicolas Murrduck
Courses Plus Student 366 Pointsi figured out myself the mistake was that i didnt include kart.drive in the try braces