Using Assertions in Python
Learn how to use assertions for error handling purposes in Python.
We'll cover the following...
Assertions are to be used for situations that should never happen, so the expression on the assert
statement has to mean an impossible condition. Should this condition happen, it means there is a defect in the software.
When assertions are used
In contrast to the error handling approach, there are situations in which we don't want our program to continue its execution if a particular error occurs. This is because, in some cases, the error cannot be overcome and our program cannot correct its course of execution (or self-heal). So it's better to fail fast and let the error be noticed, so it can be corrected in the next version upgrade.
The idea of using assertions is to prevent the program from causing further damage if such an invalid scenario is presented. Sometimes, it is better to stop and let the program crash rather than let it continue processing under the wrong assumptions. ...