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 Harnessing the Power of Objects Exceptions

What is iae.getMessage() and how does it work?

I'm following along with the lesson, and I don't understand how this code is able to return "Too many PEZ!!!" in the console:

    try {
      dispenser.fill(400);
      System.out.println("This will never happen.");
    } catch(IllegalArgumentException iae) {
      System.out.println("Whoa there!");
      System.out.printf("The error was %s", iae.getMessage());
    }

I never defined getMessage anywhere in my code, yet it still spits out the intended text. The only area where I wrote "Too many PEZ!!!" was in a different class:

public void fill(int pezAmount) {
   int newAmount = pezCount + pezAmount;
    if (newAmount > MAX_PEZ) {
     throw new IllegalArgumentException("Too many PEZ!!!"); 
    }
    pezCount = newAmount;
  }

Can someone please explain this to me?

1 Answer

iae is a custom error that you created as part of your fill() method ( throw new IllegalArgumentException("Too many PEZ!!!") ). As part of that, you told it to send the message "Too many PEZ!!!" if the error was thrown. You then ran your method within a try/catch block and told the catch block to catch any iae errors ( catch(IllegalArgumentException iae) ). Since your method apparently triggered an IllegalArgumentException error, the catch block was called, where it ran the code you defined. What you may be confused about is the .getMessage() method on iae. I don't know Java, but I assume that this is a built-in method on errors.

Hopefully this clears it up for you, but if not, just reply and I'll see if I can clarify.

Yes, thank you! I wasn't understanding that .getMessage() is a built-in method, but now I get it.