raise
is intended to invoke a Exception
at the right time. In the same way as 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
the 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 cast, with the message you passed as critical of the statement failure.
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. The two are appropriate.
In my view the most striking difference between the two is the fact that the assert
will always need a returning condition False
to invoke an exception. The raise
in turn, it is the mechanism responsible exactly for calling an exception, regardless of the condition.
An example of what I’m talking about raise
does not need to condition is the following: Imagine a class that you created to be always derived and have a certain superscript method. If it is not overwritten, I need to cast an exception warning that it is necessary to overwrite it. I would not use assert, but raise.
Behold:
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"
Realize that in this scenario raise
has its purpose completely different from assert
, since I simply want to report an error independent of conditions
+1 is the kind of question I like on this site
– Wallace Maxters
I think this question answers itself, since it has the code examples
– jsbueno
@jsbueno I think does not auto-respond no. It does not seem so obvious when you use an Exception with a
if
– Wallace Maxters
@jsbueno, the purpose of the question, is to know why there are both "error" structures, and how to implement them. Taking into account the answer, it can be said that it is not right to use the
raise
in one condition, this structure would be geared more to use in declaring abstract methods in classes (from what I understood).– Brumazzi DB
If you have said that, the answer is not good - raise causes a deliberate error and has hundreds of use cases in everyday life - far from just indicating abstract methods. But the "difference" between assert and raise is in the code snippets of the question. Maybe the question is not well written then.
– jsbueno
Related: What is assert in Python for?
– Wallace Maxters