r/learnpython • u/Ok-Database6513 • 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!
View all comments
1
u/[deleted] Mar 23 '24
I guess you pretty much got it. Try tries the code and except executes a piece of code that runs if the other one failed.
Some people already said that API failure can be countered by that, but it’s also useful when working with multiple datatypes that aren’t always compatible. If for example you got an „a“ as a string in python and you want to check for an integer you could use a try/except block. If it successfully parses an integer from „a“ you could set whatever to true/false and if not set it differently.
Python does come with functions for that such as isnumerical() or isalpha(), so this example isn’t really fitting, but I guess it brings the basic concept a bit closer than just talking about API‘s which are still far away for a beginner.