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.