+ 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?

24th May 2018, 2:17 PM
Shweta Satpathy
Shweta Satpathy - avatar
8 ответов
+ 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.
24th May 2018, 10:29 PM
John Wells
John Wells - avatar
+ 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.
16th Nov 2018, 3:29 AM
Tamoghna Saha
+ 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')
8th Jun 2018, 6:48 AM
Rugved Modak
Rugved Modak - avatar
+ 2
assertion, i try to understand but yet not understand how can and where can i used this???
27th May 2018, 5:11 PM
Prateik Jindal
Prateik Jindal - avatar
+ 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.
25th May 2018, 10:01 AM
Rugved Modak
Rugved Modak - avatar
0
I am not getting....plzz help me
8th Jun 2018, 5:14 AM
Swapna K A
Swapna K A - avatar
0
I still don't get it 😵
19th Jul 2018, 6:56 AM
Esther Omoathebu
Esther Omoathebu - avatar
0
to test if your assumption is satisfied while taking user input or while your function gives an output
18th Apr 2019, 9:17 AM
Ujjayan Roy
Ujjayan Roy - avatar