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 trialOmer Khan
1,401 Pointscan someone please help me with this challenge...
I am having compiler error. while using catch code
2 Answers
Kevin Faust
15,353 PointsHey Omer,
Here is the code you were given:
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);
}
}
What the challenge is saying that when we call the drive method, an exception will be thrown. First off, do you remember how to handle exceptions? One way that we are to use here is through try-catch blocks. We will try to run some code but if there is some sort of problem/error, we run the code in the catch block.
First, locate where the drive() method is. Surround it with a "try" block. The challenge says an IllegalArgumentException will be thrown when the code is run. That means we have to catch that exception and print it out. Seeing how you passed the previous challenge, I believe you will be able to do this. I have attached the answer if your still stumped.
public class Main {
public static void main(String[] args) {
GoKart kart = new GoKart("yellow");
if (kart.isBatteryEmpty()) {
System.out.println("The battery is empty");
}
try {
kart.drive(2);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e);
}
}
}
The e is simply just a variable for the exception to avoid rewriting "IllegalArgumentException"
Hope that helped and happy coding,
Kevin
Grigorij Schleifer
10,365 PointsVery nice answer, Kevin !!!
Thumbs up :)
Kevin Faust
15,353 PointsThnx Grigorij
Omer Khan
1,401 PointsThanks a lot Kevin
Jeremiah Montano
7,221 PointsJeremiah Montano
7,221 PointsWe would be happy to help! Please post your code so we may assist you.