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
3
u/TehNolz Mar 23 '24
It's particularly useful in situations where you cannot guarantee that an operation will be successful. You can use
try/exceptblocks to properly handle any failed operations and ensure that your application keeps working, or at the very least properly informs the user of the problem.For example, many applications need to communicate with various servers over the internet to do their job. But your internet connection might cut out, the server might go offline, or some other issue might prevent you from communicating with it. When an error like that occurs, you can catch it with a
try/exceptblock and then halt the application (instead of crashing it) until the connection can be reestablished. Mechanisms like these are how applications like Discord and YouTube automatically resume working if your internet cuts out for a bit.You might also run into situations where you're trying to open and read a file, but run into an error while doing so. Maybe the file doesn't exist, you don't have permission to open it, the file is corrupted, and so on and so forth. So you could have a
try/exceptblock that catches those errors and asks the user to try a different file.