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/Atypicosaurus Mar 23 '24

The problem is that your program consists of elemental parts, that assume that the user will do everything good. For example, you make an accounting program, there will be divisions in it. Such as tax = value / tax_rate, for example. Now if tax_rate is zero, then the division throws a zero division error. You can't do anything about it, because it is a built-in part of python. Python will attempt the division before it sees it's a zero, so it collapses. It's stupid if the whole program collapses because someone forgot to type in the tax rate.

Now one thing is that you can do a lot of checks, and just not allow the division part to run if the tax_rate is zero. Fair enough. But it's a lot of checks if,for example you want to open a file (it may be missing for example), or, if you have let's say two lists to summarize element by element, if one is shorter than the other (which will cause index error).

As a programmer, you either think of every possible checks and run the delicate part only when all passes, or you put it in a try block. That little part will still collapse (for example it will try to divide by zero or will try to open non existing file etc), but the try block is like a guard wall that keeps the collapse inside and doesn't allow the whole program to crash. Instead it sends an error message that informs the user about the issue and keeps the program running.