Date: January 4th 2016
Last updated: January 4th 2016

The raise method is known as throw in other languages (e.g. Java). The raise statement is used to flag an expression that contains an error.

For example, the assert method evaluated a logical statement to see if it was True. If it didn't, then the user would get an AssertionError.

# Input
assert 3 < 2, 'your equation is troubled'  

# Output (redacted)
# AssertionError: your equation is troubled

Another example using ValueError and the raise statement

if not (3 < 2):
    raise ValueError('this is my exception message')

# Output (redacted)
# ValueError: this is my exception message

Is ValueError something special or can I replace "ValueError" with anything I choose? No.

if not (3 < 2):
    raise HelloWorld('this is my exception message')

# Output (redacted)
# NameError: name 'HelloWorld' is not defined

There is a large list of built-in exceptions that do not have to be explicitly imported to use. Each of these exceptions can be used for error checking. Although, as stated in the docs, there is nothing to stop the user from implementing the wrong exception error. (see https://docs.python.org/2/library/exceptions.html).

if not (3 < 2):
    raise IndexError('this is my exception message')

# Output (redacted)
# IndexError: this is my exception message

Similarly I could have just called Exception which is the BaseException.

if not (3 < 2):
    raise Exception('this is my exception message')

# Output (redacted)
# Exception: this is my exception message

To reiterate, the raise statement lets a user add exceptions to signal a problem in their code. These built-in exceptions are also seen in try except code blocks.

The raise statement can be used on its own to pull up the most recent error. For example

    # list
    a = [0, 1, 2]
    # slice 
except IndexError:
    # operation after exception
    print 'Slice a[3] is out of range'
    # call the IndexError

# Output (redacted)
# IndexError: list index out of range
# Slice a[3] is out of range

Useful resources:

results matching ""

    No results matching ""