When do I use "raise" and "assert" in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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!!

23rd Apr 2019, 3:42 PM
Gabriel Felix dos Santos
Gabriel Felix dos Santos - avatar
4 Answers
+ 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.
23rd Apr 2019, 6:35 PM
Anya
Anya - avatar
+ 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.
23rd Apr 2019, 6:12 PM
HonFu
HonFu - avatar
+ 1
rajshivakoti assert raises exception if the given condition is not met.
28th Apr 2019, 6:42 PM
Akash
Akash - avatar
- 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/
25th Apr 2019, 5:01 AM
rajshivakoti
rajshivakoti - avatar