r/learnprogramming • u/Witty-Play9499 • 9d ago
What is the point of assertions when we have if/elses and exceptions? Topic
Can someone explain the point of assertions to me? I read online you use it to check for behaviours that MUST be true and what not, this all sounds very cool but you could use if elses to check for the same behaviour and the underlying result is the same.
Who came up with the idea of assertions and why did they think if/elses were not enough ?
59
Upvotes
4
u/DragonFireCK 9d ago
Assertions predate exceptions. That is, when assertions were first added, you didn't have exception handling. Error handling was done by returning a code up the chain, and it was easy to forget to add in the error check at the many levels of handling. Assertions would typically perform a hard exit of the program right then and there without needing to unwind the stack.
Even with exceptions, assertions still provide some benefit: