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 trialAnwar Rizalman
Python Development Techdegree Graduate 33,620 PointsWhy not use the try block when checking for errors?
class Die():
def __init__(self, sides=2, value=0):
if not sides >= 2:
raise ValueError("Must have at least 2 sides")
if not isinstance(sides, int):
raise ValueError("Sides must be a whole number")
Is there any reason why this style of code was used instead of the try block?
1 Answer
Chris Freeman
Treehouse Moderator 68,441 PointsGood question. A try
block is used primarily to detected errors and then handle them without causing the program to halt. In this case, there is no desire to continue so an immediate error is raised.
Post back if you have more questions. Good luck!!
Anwar Rizalman
Python Development Techdegree Graduate 33,620 PointsAnwar Rizalman
Python Development Techdegree Graduate 33,620 PointsI see. Thank you! So if I go ahead and use a try block would also be fine, correct?
Chris Freeman
Treehouse Moderator 68,441 PointsChris Freeman
Treehouse Moderator 68,441 PointsThe best place to use a try block would be surrounding the call to the
Die
function. Perhaps in the code that asks the user for the sides. Your usage may not have user input, only coder usage. In this case calling with a bad value should definitely raise the error so the code may be fixed.The
Die
function does what it can with the arguments given and throws errors on bad input since it doesnβt know how to get better input.