Assert Statements are used when:
- the final code is in theory fail safe
- the current state of the code is not yet fail safe
E.g. You programm a game with a moving car. Let's say you have a really complicated move()
function that works absolutely fine for positive input
but in special cases bugs out in weird ways for negative input
.
You know this function is going to be fine in the final stage of your game as no function part of the game will every call move()
with negative input.
But as you are currently still working on an A.I. driving the car so that you can race against bots - you cannot gurantee that you didn't make a mistake and the A.I. calls the move()
function with negative input.
Therefore you put an assert input_arg >= 0
at the beginning of your move()
function so that you get notified everytime a wrong input arg was given.
try-except
will not catch this as your movement only bugs out but does not raise an exception.
So the assert input_arg >= 0, 'input_arg must be positive!'
is just shorthand for if not (input_arg >= 0): raise ValueError('input_arg must be positive!')
while signaling that this is not an actual error that can occur in the final stage of the code but only while developing other parts of the game.
It is shorter, can be differentiated from 'real' errors and therefore also automatically stripped away for production code.