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

Throw only worked when I instantiated the exception within. Why?

The following did work :

throw IllegalArgumentException ("Not enough battery remains");

The following did not:

IllegalArgumentException iae = new IllegalArgumentException (); if (mBarsCount - laps < 0) { throw iae ("Not enough battery remains"); }

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

1 Answer

Enrique Munguía
Enrique Munguía
14,311 Points

The problem occurs when you throw the exception, you must throw the object iae, the parenthesis and message are wrong. If you want to include the message do it when your first create the exception object, like this

IllegalArgumentException iae = new IllegalArgumentException ("Not enough battery remains"); 
if (mBarsCount - laps < 0) { 
   throw iae; 
}

I don't recommend that style, though, because you always create an object even in the case where you will not throw the exception. This is what I'd do:

if (mBarsCount - laps < 0) { 
   throw new IllegalArgumentException ("Not enough battery remains"); 
}