+ 3
When do I use "raise" and "assert" in Python?
I'm studying exceptions and would like to know the differences of raise/assert staments. For example, both are used to check a condition out and throw an exception case the condition is true. However, is there some logic difference to use them or both are equals (being the sintax the unique difference)? Thank you!!
4 odpowiedzi
+ 5
HonFu just explained well so i will make only some comments about it.
Be very careful to use assert to debugging. You will be in a very bad situation if you write the check condition wrongfully.
This remember me Dafny language. In Dafny you have a automated theorem prover to assist you to write correct code.
The problem is that the prover help only if you correctely type the condition to be proven. So you technically have two times more chance to write your code wrong.
+ 4
assert is only used for debugging. Depending on what mode your program runs in, assert statements may be ignored completely, so your program flow must not depend on assert!
To control what can go wrong in a program (file didn't open, user input faulty etc.) you use exceptions.
+ 1
rajshivakoti assert raises exception if the given condition is not met.
- 1
Raise is typically used when We have detected an error condition or some condition does not satisfy. Assert is similar but the exception is only raised if a condition is met.
raise - raise an exception.
assert - raise an exception if a given condition is meet.
http://pythonandmltrainingcourses.com/courses/best-diploma-in-JUMP_LINK__&&__python__&&__JUMP_LINK-course-in-delhi/