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

Looks like you didn't catch the exception.

What i am doing wrong here please somone it keeps saying that i didnt catch the exception

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(9);
        }   catch  (IllegalArgumentException iae) {
        System.out.printf("%s\n", iae.getMessage());
      }

        }
    }

i figured out myself the mistake was that i didnt include kart.drive in the try braces

Aditya Puri
Aditya Puri
1,080 Points

hey!! 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?

Hi 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
Aditya Puri
1,080 Points

SO, 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?

Yes. 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.

2 Answers

Hi 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.

Yea i figured out Thanks!!! Steve Hunter