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

Russell Brookman
Russell Brookman
3,118 Points

I am really stuck

They want me to find the Exception in this. Until this point I though i knew what I was doing. I was wrong.

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); } }

2 Answers

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

Hi there! Well the basis for this is that you need to wrap what you're going to try to do in a try catch block. We need to try the code and then if it fails catch the exception. So when the battery is empty but we try to drive the cart 2 more laps... there can and should be a problem. Here's how I did it:

public class Main {
    public static void main(String[] args) {
        GoKart kart = new GoKart("yellow");
        try {   //start the try here
          if (kart.isBatteryEmpty()) {
            System.out.println("The battery is empty");
          }
          kart.drive(2);  //try and drive the kart  this will create a problem
        }
        catch (IllegalArgumentException iae) {  //catch the Exception and handle it
          System.out.println(iae);
        }
    }
}

Hope this helps! :smiley:

edited for additional note

The reason this doesn't necessarily print out the battery is empty message. Imagine that the battery isn't empty, but we only have enough for one lap left. Then we have a problem. That's what we're looking for here :thumbsup:

Russell Brookman
Russell Brookman
3,118 Points

Wow, thanks. I'll give it a shot.