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.

Python Python Basics Functions and Looping Raising Exceptions

Cody Stephenson
Cody Stephenson
7,771 Points

Why leverage errors at all to handle some of the disallowed inputs instead of just using more if/try/else logic?

What is the purpose of leveraging errors (in this case the ValueError) instead of just specific logic in a try block? Something like

if input <=1 
   print("message about needing more than one person")
if input > 1 
   print("successful message with calculated value")
else
   print("message about not being a valid input")

Is the purpose as fundamental as trying to avoid actually running through pieces of code?

1 Answer

Hi Cody!

I can't really explain it other than that's just how they do it.

The real point is to handle exceptions in a way that can guide users with appropriate feedback without bringing the program execution to a grinding halt.

Usually, it helps to do it in a while loop, so you can keep prompting the user until valid input is provided.

Perhaps I can better explain it with an example:

https://teamtreehouse.com/community/all-together-now-the-project (check my beyond-the-challenge code).

More info:

https://www.w3schools.com/python/gloss_python_raise.asp

https://realpython.com/python-exceptions/

And by the way, if you are interested, I can provide you my code for a python program I wrote to explore the "Monty Hall Game " Problem Paradox - it has A LOT of error handling/exceptions.

As seen here:

https://www.khanacademy.org/math/precalculus/x9e81a4f98389efdf:prob-comb/x9e81a4f98389efdf:dependent-events-precalc/v/monty-hall-problem (and in the movie 21).

I hope that helps.

Stay safe and happy coding!

Cody Stephenson
Cody Stephenson
7,771 Points

I understand the logic of creating conditional responses if the input doesn't sense, but I'm wondering what the purpose of elevating and handling it as a custom exception is vs just handling it conditionally. It seems like an extra step if the input wouldn't actually break anything.