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

Anusha Singh
PLUS
Anusha Singh
Courses Plus Student 22,106 Points

I don't understand why it gives this error

The question is {"The code in Main.java is going to throw an IllegalArgumentException when the drive method is called. Catch it and warn the user."} I don't know why it gives the error that "Looks like you didn't catch the exception". Please help!

Main.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);

      try {
       kart.drive(2); 
      } catch (IllegalArgumentException iae) {
        System.out.printf("The error was: %s\n", iae.getMessage());
    } 

}

1 Answer

Jennifer Nordell
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
Jennifer Nordell
Treehouse Teacher

Hi there Soma Singh ! You're doing great. There's a couple of things going on here and one of them I think was with the pasting of your code. In the code that you've posted there's an ending curly brace missing. But, that produces a different error message than the one you're getting.

The reason that you're getting that message is because you run kart.drive(2) not once... but twice. And the first time you run it, it doesn't catch the exception.

So if you add back in the end curly brace and remove the first kart.drive(2), your code passes! Take a look here:

public class Main {
    public static void main(String[] args) {
        GoKart kart = new GoKart("yellow");
        if (kart.isBatteryEmpty()) {
          System.out.println("The battery is empty");
        }
                         //note that kart.drive(2) has been removed here
      try {
       kart.drive(2); 
       } catch (IllegalArgumentException iae) {
        System.out.printf("The error was: %s\n", iae.getMessage());
       } 
    }
}

Hope this helps! :smiley: