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

Mathieu Payment
Mathieu Payment
1,404 Points

I did write the command exactly like in the video... why is this not working?

the error in preview point the the c in the word catch...

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);
    } catch (IllegalArgumentException noBattery){
      System.out.print(noBattery);
    }
}
Jonathan Mitten
Jonathan Mitten
Courses Plus Student 11,197 Points

You do not have a try block. I would recommend you review the try / catch logic in the Handling Exceptions video.

2 Answers

andren
andren
28,558 Points

Exception handling is done by wrapping code in what is called a Try/Catch block, your catch block looks pretty decent but you seems to have forgotten about the Try part of the Try/Catch mechanism.

You need to add a Try block that wraps the code you are expecting to throw an exception, and then attach the catch block to that try block like this:

Try { // Add a Try block that wraps the exception throwing code
    kart.drive(2);
} catch (IllegalArgumentException noBattery) { // Attach the Catch block to the end of the Try block.
    // You also need to call the getMessage method on the error object in order to get the error message.
    System.out.print(noBattery.getMessage());
}
Mathieu Payment
Mathieu Payment
1,404 Points

thanks for both reply. I did indeed skip this step.