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 trialPerdana Anwar
889 PointsWhy 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;
}
2 Answers
Craig Dennis
Treehouse TeacherYou 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
1,204 PointsI 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 .
Jose Cortedano
409 PointsJose Cortedano
409 PointsLike 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.