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

Paul Taylor
Paul Taylor
2,213 Points

Not finding the exception

Its wanting to find the exception i'am not finding tried multiple things and no success, what am I missing?

Main.java
public class Main {
    public static void main(String[] args) {
        GoKart kart = new GoKart("yellow");
        if (kart.isBatteryEmpty()) {
          System.out.printf("The battery is empty");
        }
        kart.drive(2);
    }
}

2 Answers

Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,497 Points

I was able to get it to work using this code:

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(100);
    } catch (IllegalArgumentException iae) {
       System.out.println("Alert");
       System.out.printf("There was an error: %s\n", iae.getMessage());
    }

}

}

Durim Kryeziu
Durim Kryeziu
14,002 Points

Hi Paul,

First read carefully the question:

The code in Main.java is going to throw an IllegalArgumentException when the drive method is called. Catch it and warn the user.

It tells you you're going to have an exception thrown from that code... it tells you that the problematic method is drive(). When they ask you to Catch it..., it means you have to encapsulate the kart.drive(2) part of code with the try...catch block and even it shows you which exception type to catch: ...IllegalArgumentException...

Till now you know that you have to encapsulate the kart.drive(2) code with try...catch block like this:

try {
    kart.drive(2);
} catch (IllegalArgumentException e) {
}

Because they ask you to ...warn the user. then you have to provide a useful message on the body the of catch block like this:

try {
    kart.drive(2);
} catch (IllegalArgumentException e) {
    System.out.println("An error has occurred while trying to call drive() method" + e.getMessage());
}

Tried to explain a bit, hope it helps :D

Happy coding!