+ 4
Raise exceptions and assertions in Python
I would like to try to understand what this is for, it seems to me that it is a very abstract concept, I tried to investigate but I really don't understand anything, it seems to be very useful to handle the exceptions in Python but I would like to understand this in depth, I appreciate very much if you have easy to read or see resources to understand this topic, thank you very much.
3 Answers
+ 9
Hereâs a simple example so you can see where assertions might come
in handy. I tried to give this some semblance of a real-world problem
you might actually encounter in one of your programs.
Suppose you were building an online store with Python. Youâre working to add a discount coupon functionality to the system, and eventually you write the following apply_discount function:
def apply_discount(product, discount):
price = int(product['price'] * (1.0 - discount))
assert 0 <= price <= product['price']
return price
Notice the assert statement in there? It will guarantee that, no matter what, discounted prices calculated by this function cannot be lower than $0 and they cannot be higher than the original price of the product .This speeds up debugging efforts considerably.and it will make your
programs more maintainable in the long-run. And that, my friend is
the power of assertions.
+ 7
Why Not Just Use a Regular Exception?
Now, youâre probably wondering why I didnât just use an if-statement
and an exception in the previous exampleâŠ
You see, the proper use of assertions is to inform developers about
unrecoverable errors in a program. Assertions are not intended to
signal expected error conditions, like a File-Not-Found error, where
a user can take corrective actions or just try again.
Assertions are meant to be internal self-checks for your program. They
work by declaring some conditions as impossible in your code. If one
of these conditions doesnât hold, that means thereâs a bug in the program.
If your program is bug-free, these conditions will never occur. But if
they do occur, the program will crash with an assertion error telling
you exactly which âimpossibleâ condition was triggered. This makes
it much easier to track down and fix bugs in your programs. And I like
anything that makes life easierâdonât you?
For now, keep in mind that Pythonâs assert statement is a
debugging
aid.
+ 2
Try this https://www.questarter.com/q/is-it-a-good-practice-to-use-try-except-else-in-JUMP_LINK__&&__python__&&__JUMP_LINK-27_16138232.html
Good luck learning Python!