+ 8
Why do we need assertions?
even when we have concept like exception handling using different blocks , why and when do we go for assertion?
8 Antworten
+ 12
I've been programming for 45 years and never used assertions. People who do use it do so because it can test your assumptions during testing of your code and be turned off during production. For example, if your function/method must only get positive numbers and the user isn't able to have access to the argument. You don't need to test it once the code is working.
+ 6
Many confuse assertion with try/except because deep down, they both do the same thing. However, exceptions address the robustness of your application while assertions address its correctness.
Assertions should be used to check something that should never happen while an exception should be used to check something that might happen (something in which you don't have control like user input).
NOTE: The thumb rule is that use assertions when you are trying to catch your own errors and exceptions when trying to catch other people's errors.
+ 5
Okay I'll try to give an example
a = input('Enter a positive integer: ')
try:
a = int(a)
# Method 1 to check positive
if not a >= 0: # or if a < 0
raise ValueError # or any error because we have generalized the exceptions in except block
# or direct print
print('Invalid input')
# Method 2
assert a >= 0
# that's it. one statement. get out immediately.
except:
print('Invalid input')
+ 2
assertion, i try to understand but yet not understand how can and where can i used this???
+ 1
An assert statement can be used to immediately exit the program. I don't know if this is a correct example but assume you have an app which is in the market but it is under maintainance, so you don't want people to use it for some time. You can simply use an assert statement which will give people your message and end program immediately.
0
I am not getting....plzz help me
0
I still don't get it 😵
0
to test if your assumption is satisfied while taking user input or while your function gives an output