Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java

IllegalArgumentException, printing error to console?

I was tasked to catch a IllegalArgumentException, now they me want me to print the error to the console.

This is my code, i added the println & printf at the bottom be i still get: Bummer! Please print out the exception's message to the console using the System.out object

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(20); } catch (IllegalArgumentException iae) { System.out.println("A error occurred!"); System.out.printf("The error was: &s\n", iae.getMessage()); } } }

Why does my code no work?

I believe the main issue is that you are using &s instead of %s

But even then, it seems the code won't print an error because the exception is not getting thrown. Here is a sample I put together to throw and exception. The pasting may not be perfect.

class GoKart { private String color; public String getColor() { return color; }

public void setColor(String color) {
    this.color = color;
}

public GoKart(String color) {
    this.color = color;
}

public void drive(int speed) {
    if(speed < 10) {
        System.out.println("going " + speed + " miles per hours");
    }else {
        throw new IllegalArgumentException("An error occurred!");
    }

}

public boolean isBatteryEmpty() {
   return true;
}

} public class test { public static void main(String[] args) { GoKart kart = new GoKart("yellow"); if (kart.isBatteryEmpty()) { System.out.println("The battery is empty"); } try { kart.drive(20); } catch (IllegalArgumentException iae) { System.out.println("A error occurred!"); System.out.printf("The error was: %s\n", iae.getMessage()); } } }

hope this helps