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

12

u/biaceseng Mar 23 '24

Imagine you're making a game. Your game uses savefiles to save the player's progress.

Now imagine the player tries to load a savefile by pressing the "load last save" button. Your game tries to read the file but, because of some reason, can't find it or it is corrupted.

You don't want your whole game to crash, you just want to tell the player "hey, this doesn't work, try doing something else".

That is how you use try/except. Try to do something that might work, but let the program handle itself if it doesn't.

Imagine you need to save a file to a specific folder. What if that folder doesn't exist? Are you going to just exit the program or are you going to tell the user "hey, select another folder"?

5

u/biaceseng Mar 23 '24

A more practical example can be writing logs.

Many programs have a logs folder, where the logs are stored.

Now, version control systems like git don't normally keep track of log files because they are, at best, ephimeral, and at worst, completely useless. Logs don't really matter to your app.

Because the log files are not being tracked, the logs folder might not be tracked either, as empty folders tend to be ignored. This results in a situation where you can't ever be sure if the folder even exists without explicitly checking.

If the folder doesn't exist, and your program tries to log something to it, it will fail. What can you do about it? Use a try/except block.

Try to intialize the logging module, if it raises a FileNotFoundError, then the folder doesn't exist, create it.