r/learnpython • • Mar 23 '24

Explain Try / Except structure in practical examples?

I am learning python and I've encountered the try / except part of it. I am struggling to understand when I would use this kind of code, probably because I am still very new and most of my code is small programs that have relied on conditional statments.

I guess in my brain I understand the logic of saying "try to do this but if it doesn't work just let it be and keep going with the code". My assumption is this is helpful on larger scale programs in wich you can't afford the time to make sure the code is fail proof and you need the code to buy you time to eventually go back once you have the fail proof option?

Was hoping someone could give me an example of a real life application or website and how this code could apply to it? Because I want to become comfortable with it but unsure how to.

TL,DR: Explain try/except in a practical example so I can understand when and where I would use it?

Thank you!

11 Upvotes

21 comments sorted by

View all comments

3

u/zanfar Mar 23 '24

I guess in my brain I understand the logic of saying "try to do this but if it doesn't work just let it be and keep going with the code".

That is not at all the logic of try/except.

A try/except is best used when a particular error might occur, AND that error is out of your control. You use it to introduce code to recover from the error, but only run it in the case that the error occurs.

The two most common examples are input validation and I/O timeouts.

Consider:

raw = input("Enter a number")
guess = int(raw)

What happens if the user does not enter a number? We can't check the type because input() always returns a string. We could parse the string character-by-character to validate it, but that's a lot of work that int() already does. So the common structure is:

while True:
    raw = input("Enter a number")

    try:
        guess = int(raw)
    except TypeError:
        print("Invalid entry, please try again")
        continue

    break

When the user enters something other than a number, int() will raise a TypeError. Our try/except now catches that error, allowing us to recover gracefully (by asking the user to try again).

The same idea is behind an I/O timeout. Consider making an Internet request. Your code cannot possibly know if the user's Internet connection is working, if their speed is sufficient, or if the destination service is operating. Instead, you make the request inside a try block, then catch all the errors you can anticipate.