Python 3 - raise statement

user8048576 picture user8048576 · May 22, 2017 · Viewed 13.5k times · Source

I am currently working through Learning Python by Mark Lutz and David Ascher and I have come across a section of code that keeps bringing up errors. I am aware that that book was written with Python 2 in mind unlike the Pyhton 3 I am using. I was wondering if anyone knew a solution to my problem as I have looked everywhere but I have been unable to find a solution .

.........................

MyBad = 'oops'

def stuff( ):
    raise MyBad

try:
    stuff( )
except MyBad:
    print('got it')

Answer

Right leg picture Right leg · May 22, 2017

Basically, MyBad is not an exception, and the raise statement can only be used with exceptions.

To make MyBad an exception, you must make it extend a subclass of Exception. For instance, the following will work:

class MyBad(Exception):
    pass

def stuff( ):
    raise MyBad

try:
    stuff( )
except MyBad:
    print('got it')

Output:

got it

However, it's better to raise an instance of an exception class, rather than the class itself, because it allows the use of parameters, usually describing the error. The following example illustrates this:

class MyBad(Exception):
    def __init__(self, message):
        super().__init__()
        self.message = message

def stuff(message):
    raise MyBad(message)

try:
    stuff("Your bad")
except MyBad as error:
    print('got it (message: {})'.format(error.message))

Output:

got it (Your bad)