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 trial

Java Java Objects (Retired) Harnessing the Power of Objects Handling Exceptions

can someone please help me with this challenge...

I am having compiler error. while using catch code

We would be happy to help! Please post your code so we may assist you.

2 Answers

Kevin Faust
Kevin Faust
15,353 Points

Hey Omer,

Here is the code you were given:

GoKart.java
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.

Answer.java
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
Grigorij Schleifer
10,365 Points

Very nice answer, Kevin !!!

Thumbs up :)

Thanks a lot Kevin