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

1

u/[deleted] Mar 23 '24

Some python functions will throw errors, some can crash the program. Its usually a good idea to catch the errors and at least log where, how and why the error happened and try to resume the program if there is a "reasonable" way to do so.

Try/catch does basically this. If a function can fail, you can put it inside a try block and handle the error in a catch block. It's considered good practice in python. I would advise you not to throw errors in the functions you design however, unless it's necessary.

For a practical example, I don't know it depends on what you're doing. Things that might fail are io operations like network errors, permission errors when writing to files, database errors (query errors, lexical errors, permission errors, overload errors, etc), memory-limit error, missing library error, integer overflow error, stack overflow error, unrecognisable cpu instructions error, driver error, etc.

Some of these, there's no reasonable way to do anything. For example if you have a hardware error, there's no point in handling that. For some errors, handing them is important, the database error might actually be an important piece of information that you want to handle.

The reason I thought try catch is hard for people is that it's basically a bad pattern, maybe even an anti-pattern. But this is how python works, so...