raise
is intended to invoke a Exception
at the appropriate time. Like other languages when we use throw new Exception
, the exception is invoked the moment we call raise
.
Example:
raise Exception('Invoquei')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: Invoquei
assert
in turn makes a statement and, if it fails (ie returns False
), invokes an Exception.
This statement occurs as follows: If true, the next line continues to run normally. If False, the exception is thrown, with the message you passed as a critique of failure to affirm.
Example:
a = 1 + 1
assert a == 2, 'Conta está errada'
assert a == 3, 'Conta está errada' #Exceção é lançada aqui, pois é falso
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError: Conta errada
I believe that in your case, because it is a simple example, the logic used to critique the argument passed to the function, makes no difference. Both are appropriate.
In my view the most striking difference between the two is the fact that the assert
% will always need a condition returning False
to invoke an exception. The raise
, in turn, is the mechanism responsible for exactly calling an exception, regardless of the condition.
An example of which I am saying that raise
does not need condition is this: Imagine a class that you have created to always be derived and have a certain method overwritten. If it is not overwritten, I need to throw an exception warning that it needs to be overwritten. I would not use assert, but raise.
See:
class abstrata(object):
def metodo(self):
raise "Esse método precisa ser implementado na classe filha"
class concreta(abstrata):
def metodo(self):
return "implementei com sucesso"
Note that in this scenario raise
has its purpose completely different from assert
, since I simply want to report a condition-independent error