Type Error with raise statement

2

I'm trying to write a very simple function that I saw in the book "Learn to think like a programmer with python":

def elige_numero():
    x = input("Escriba un número: ")
    if x == str(17):
        raise('ErrorNumeroMalo', 'El 17 es malevolo')
    return x

The problem is that when in the input I put the number 17 I get the error:

  

TypeError: exceptions must derive from BaseException

Does anyone know what happened and how to fix it?

    
asked by MahaSaka 16.09.2017 в 17:38
source

1 answer

3

What happens is that the exception ErrorNumeroMalo is not defined (at least not in the code you present). So since it does not exist, the interpreter thinks that maybe you have written wrong the exception you are trying to throw.

The way to solve it is to define the exception. It is usually done with a class that inherits from the class BaseException , as indicated by the interpreter. Within the scope of your script, I think something like this would work:

class ErrorNumeroMalo(BaseException):
    def __init__(self, message):
        self.message = message

And your script would look something like this:

def elige_numero():
    x = input("Escriba un número: ")
    if x == str(17):
        raise ErrorNumeroMalo("El 17 es malévolo")
    return x

You can check the official BaseException documentation , you know, just for Know a little more. You can also check the official Python documentation, how to create your own exceptions .

    
answered by 16.09.2017 / 17:42
source