What is an example of try/except?

In the lesson, we are taught that “try” and “except” statements are used to check for possible errors a user might encounter. However, I suppose that the process of checking errors does not fulfill the final scope of any control flow, but it is just used complementary in order to write a clean code without errors.
If this right, I would expect that “try” and “except” statements would be used in conjuction with other statements such as “if, else” etc, all written in the same code/function.
So, my question is , which is the right order to combine all these statements when writing the parts of a function? Could you please give an example?

the vital piece of information missing here is that we can also throw exceptions:

def validate_username(username):
    if ( len(username) < 5 ):
        raise Exception("Username to short")
    
    
def main():
    username = raw_input("input username: ") # replace with input if you use python3
    try:
  	    validate_username(username)
    except Exception as e:
        print(e)
main()

this also explains what happens when exceptions occur.

you could expand the validate_username() function with a lot more exceptions, so then the control flow logic (if, elif, else) is within the validate_username, then other people can use your function handle the exception as they like.

8 Likes

def raises_value_error():
raise ValueError

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

Do we need indent "try"and “except”? If they are statements like “if” in a function, why is the indention different ?

1 Like

try and except have the same nesting rules? When you want a try/except statement within an if statement you get:

if some_condition:
    try:
        # some code
    except SomeException:
        # something to do when the exception occured

I do not see any result on console for my code. Please help me to know where I made a mistake.

Your indention/nesting is off. print(shipping_cost_drone(1.5)) is nested in the body of the function itself, and unreachable after a return statement, just to name one thing.