-1

following code in python 2.7.10

def inputnumber() :
    x = input('pick a number : ')
    if x == 17 :
        raise 'BadNumberError' , '17 is a bad number'
    return x

and when i run this , it gives me TypeError :

TypeError: exceptions must be old-style classes or derived from BaseException, not str

pejman
  • 17
  • 7

1 Answers1

0

The issue is that this is not how exceptions are raised in Python. You raise an object that is derived from BaseException (generally it is derived from one of the built-in exception types. So, your example would be retooled like this:

class BadNumberError(ValueError):
    pass

def inputnumber():
    x = input('Pick a number: ')
    if x == 17:
        raise BadNumberError('17 is a bad number')

    return x

The results being:

[/home/.../Python/demos]$ python2.7 exception_demo.py 
Pick a number: 17
Traceback (most recent call last):
  File "exception_demo.py", line 11, in <module>
    print(inputnumber())
  File "exception_demo.py", line 7, in inputnumber
    raise BadNumberError('17 is a bad number')
__main__.BadNumberError: 17 is a bad number
[/home/.../Python/demos]$ python2.7 exception_demo.py 
Pick a number: 18
18

One thing to note is that it is extremely common to see people just using instances of the built-in exception types directly, like this:

def inputnumber():
    x = input('Pick a number: ')
    if x == 17:
        raise ValueError('17 is a bad number')

    return x

It's presumably more convenient, though I personally don't love it, since it makes it difficult to catch exceptions caused by specific conditions.

Paul
  • 9,014
  • 9
  • 41
  • 75