Q:

Writing Personalized Error Messages in Python

I'm a user of R, but have to learn Python for a school project. Now, in R, I frequently use the base function stop in my code, and I'd like to know how to emulate this functionality in Python. For a concrete example, take this R code:
add.two <- function(t) {
     if (!is.numeric(t)) stop('Please make t numeric.')
     t + 2
}

This function does three things, (i) it adds two to (e.g.) a numeric vector, (ii) if it is passed a non-numeric argument it returns a personal, concise, and easy to understand error message, and (iii) it ceases the function from running any further in the case that t is non-numeric.
My first attempt for how to do this in Python is
def add_two(t):
    if not ( isinstance(t, int) or isinstance(t, float) ):
        print('Error: Please make t numeric.')
    else:
        print(t+2)

However, this only does things (i) and (ii). In other words, if the body of this function were longer (although, in this example, it is not), Python would not know to stop running. Another option is
def add_two(t):
    if not ( isinstance(t, int) or isinstance(t, float) ):
        print('Error: Please make t numeric.')
        raise
    else:
        print(t+2)

Which, I suppose, does things (i) and (iii), but the error message is at best cluttered and confusing, and at worst incorrect and misleading.
Does someone know of a way to achieve all three goals in Python? Thank you for your time.
Edit: IDK why, I said 'error' instead of 'stop' just a brain fart.

A:

Use the raise keyword while creating an Exception object. You can customize the message with an argument:
def add_two(t):
    if not (isinstance(t, int) or isinstance(t, float)):
        raise ValueError('t must be numeric')
    else:
        print(t + 2)

Like most programming languages, there are different types of exceptions to represent different types of faults. The list of those is here, and you can of course make custom Exception subclasses if you want your own custom exception types.

In your case, though, this isn't so much necessary. If you do
def add_two(t):
    print(t + 2)

then an error will be thrown anyway if t is of a type that you can't add an integer to (e.g. a string - a TypeError will be raised). Python typically advocates doing this when possible: "ask forgiveness rather than permission". 

