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!

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

Vinayak Gadag
Vinayak Gadag
749 Points

exception while catching

Getting exception while catching the exception

Main.java
public class Main {
    public static void main(String[] args) {
        GoKart kart = new GoKart("yellow");
      try{
        if (kart.isBatteryEmpty()) {
          System.out.println("The battery is empty");
        }
      }
        catch(IllegalArgumentException iae){
        System.out.println("Whoa!!!");
        System.out.printf("The error was: %s\n", iae.getMessage());
      }
        kart.drive(2);
    }
}
Ross Logan
Ross Logan
8,131 Points

Hi,

can you provide more details? What exception is it that you are getting when the catching the exception? Would also be helpful if you pasted the code for the GoKart class, in particular the isBatteryEmpty() method

1 Answer

VERY close. Your problem is the try catch was for the "drive" method and not the if statement. All I did was move the try catch around for you.

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); //What you needed to test <-------------------------------------------------------
        }
        catch(IllegalArgumentException iae) {
            System.out.println("Whoa!!!");
            System.out.printf("The error was: %s\n", iae.getMessage());
         }
    }//end main method
}//end class
Vinayak Gadag
Vinayak Gadag
749 Points

Thank you Philip. I figured it out later and completed the task.