![](/img/trans.png)
[英]raise *error doesn't work in Python 2.7; how can I raise a previously captured exception?
[英]How do I raise my own Exception in Python 2.7?
我從Python教程書中復制並粘貼了這些代碼行。 當我嘗試在PyCharm中運行它時,為什么此代碼不起作用?
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
您可以使用標准異常:
raise ValueError('17 is a bad number')
或者,您可以定義自己的:
class BadNumberError(Exception):
pass
然后使用它:
raise BadNumberError('17 is a bad number')
如果已經定義了BadNumberError
類異常,則應該按如下方式引發異常BadNumberError('17 is a bad number')
。
如果還沒有
class BadNumberError(Exception):
pass
這是文檔,其中包含有關引發異常的信息
只要繼承自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
如果要定義自己的錯誤 ,則必須執行以下操作:
class BadNumberError(Exception):
pass
然后使用它:
def inputNumber ():
x = input ('Pick a number: ')
if x == 17:
raise BadNumberError('17 is a bad number')
return x
inputNumber()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.