Python, difference between assert and raise?

8

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

In the code below shows the implementation of 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 use and implementation between assert and raise

    
asked by anonymous 06.05.2016 / 02:55

1 answer

9

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

    
06.05.2016 / 02:58