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 Exceptions

Perdana Anwar
Perdana Anwar
889 Points

Why use an exception to find errors?

What would be the benefit of using an exception over an if else like this...

     if (newAmount > MAX_PEZ) {
     System.out.println("Too many PEZ!!!");
   } else {
       System.out.println("Pez added");
       mPezCount = newAmount;
     }
Jose Cortedano
Jose Cortedano
409 Points

Like Craig mentioned this can be used to try an input and test conditions similar to else. How would your code above work if it was user input and the number input was a letter? Try and catch could be used to ask the user for more input and continue the a loop.

2 Answers

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

You are correct that your code would work, however, throwing exceptions allow any user of your object to handle the exception however is most appropriate in their application. Your code, because it is so good, can and will be executed in many different scenarios..

Does that make more sense?

cmrtb
cmrtb
1,204 Points

I know when I started to learn exceptions in Python (maybe it was PHP) I didn't understand why? I think it dawned on me when I was using somebody else's code and I saw their "throw" that I realized, I can use this exception how I see fit. I could run different part of the code. I could make sure that my program didn't stop just because of the exception, or if it was critical, make sure certain tasks were taken care of before program was closed. And/or the exception didn't even actually have to be a "problem", but could be used to do something else.

At the same time, Craig's answer seems like a better answer :p .