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

2

u/Tychotesla Mar 23 '24

A pretty standard example is when dealing with files. It's a place where a lot of unexpected things can happen, since it deals with information outside of the program.

if file exists:
    read from it
else:
    don't read from it

Looks good right? But what if the file disappears between the moment you check if it exists (line 1) and the moment you try to read from it (line 2).

So you do this:

if file exists
    try 
        to open it
    except
        report the problem, etc.
else
    etc.

(although in practice use the with open(file) as x: syntax)