Inquiry on Try and Except Statements

https://www.codecademy.com/paths/computer-science/tracks/cspath-flow-data-iteration/modules/dspath-control-flow/lessons/python-control-flow/exercises/try-and-except-statements

Take a look at this script:

def raises_value_error():
(indention) raise ValueError

try:
(indention) raises_value_error()
except ValueError:
(indention) print(“You raised a ValueError!”)

Why is the try and except statement outside the scope of the raises_value_error()? Is it cleaner to write it this way? Would it be wrong to write the try and except statements inside the function? I wouldn’t have been able to do this without prior knowledge.

Regards,
MP

HI @mosespark.
Regarding indenation and formatting check this post, it will help in the future- FAQ-formatting.

I assume this script is intended to just show the basics of how try, except and raise might be used with a function that always raises a specific exception. I’m not really sure what you’d be using try and except on in this particular function if you moved them but you could certainly explore their usage with your own functions.

If your questions is a little more generalised about where to use try & except etc. there’s no one-size-fits-all rule for handling errors. It often differs between projects and is influecned heavily by the overall purpose of your code; for now it’s probably best to just continue with the lessons which I assume add more detail (potentially some sensible examples too).

Keep a note of it by all means for something to look into in the future though if you don’t feel the lessons have covered enough for you, there’s numerous posts, blogs, guides and book chapters devoted to handling errors.

I was still confused about where I should write the try and except. Would it be okay to write it inside the function? I don’t know if the organization makes a difference.

All that function does is raise a specific error. You certainly can stick an error check inside it but you may as well explore this with a slightly more exciting function, this one exists solely as proof of concept.

So a rough answer would be you can do both. Ideally error catching occurs as close as possible to the location of the erroneous code so as to ease debugging, however in certain cases you may simply want to log an error without interrupting operation or perhaps just raise it to the main code block.

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.