Python, difference between assert and raise?


I came across a question with the raise and assert structures in python.

The code below shows the implementation of the structures forcing an error if the number passed is negative.

def is_neg_assert(int):
    assert (int >= 0), "Número negativo"

def is_neg_raise(int):
    if int < 0:
        raise "Número negativo"

Both will force the error if the value passed is less than 0 .

What is the difference in usage and implementation between assert and raise


raise is intended to invoke an Exception at the appropriate time. As with other languages ​​when we use throw new Exception , the exception is called the moment we call raise .


 raise Exception('Invoquei')

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
Exception: Invoquei

the assert in turn makes an assertion and, if it fails (that is, returns False ), throws an Exception.

This statement occurs as follows: If true, the next line continues to execute normally. If it's False, the exception is thrown, with the message you passed as critical of the assertion failure.


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, as it is a simple example, the logic used to criticize 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. raise in turn, is the mechanism responsible for exactly calling an exception, regardless of the condition.

An example that I'm saying raise doesn't need a condition is the following: Imagine a class you created to always be derived and have a certain method overridden. If it doesn't get overwritten, I need to throw an exception notifying me that I need to overwrite it. I wouldn't use assert, I would raise.


  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 , as I simply want to report an error regardless of conditions

Scroll to Top