2016-09-22 74 views
0

我從Pyhton教程手冊中複製並粘貼了這些代碼行。爲什麼當我嘗試在PyCharm中運行它時,這段代碼不起作用?在Python中引發我自己的異常2.7

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

這是我當我運行代碼:

Pick a number: 17 
Traceback (most recent call last): 
    File "C:/Users/arman/Desktop/Scribble/Hello.py", line 153, in <module> 
    inputNumber() 
    File "C:/Users/arman/Desktop/Scribble/Hello.py", line 151, in inputNumber 
    raise 'BadNumberError', '17 is a bad number' 
TypeError: exceptions must be old-style classes or derived from BaseException, not str 
+4

該教程是*非常過時*的然後。你想選擇一個不同的教程。代碼在不產生棄用警告的情況下工作的最後一個Python版本是Python 2.2(2001年發佈),支持從2.6(2008)完全刪除。使用概念和語法的教程*遠遠落後於時代*也會有其他問題。找到比〜15歲更新的東西。 –

+0

另外,如果您剛剛開始使用Python,我建議您從Python 3開始,而不是2. Python 2已停止使用,2.7將僅在2020年之前收到安全修復程序。Python 3是所有能源都要去的地方至。 –

+0

我一直想學習更新的版本,但有這個機器視覺課程,我花了這個學期,需要Python 2.7編程... – Arman

回答

0

你應該引發異常的加薪如下BadNumberError('17 is a bad number')如果您已經定義BadNumberError類異常。

如果你沒有,那麼

class BadNumberError(Exception): 
    pass 

這裏是docs與信息有關引發異常

+0

只要有這樣一個異常類。那沒有。 –

+0

@MartijnPieters你是完全正確的,我已經更新了答案。謝謝! –

+0

我強烈懷疑OP會發現其他問題。 Python 2.2及更早版本是迄今爲止的古代歷史。 –

0

Exception類就繼承,那麼你就可以拋出自己的異常:

class BadNumberException(Exception): 
    pass 

raise BadNumberException('17 is a bad number') 

輸出:

Traceback (most recent call last): 
    File "<module1>", line 4, in <module> 
BadNumberException: 17 is a bad number 
0

如果要定義一個your own error你要做的:

class BadNumberError(Exception): 
    pass 

,然後使用它:

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

您可以使用標準的例外:

raise ValueError('17 is a bad number') 

或者你可以定義你自己的:

class BadNumberError(Exception): 
    pass 

,然後使用它:

raise BadNumberError('17 is a bad number')