Python 2.7.3如何定義錯誤類?
當我爲像鸚鵡一樣的用戶運行SillyWalk.getGroups(user_id = user)
時出現以下錯誤。
Traceback (most recent call last):
File "C:\Python\API\getgroups.py", line 32, in <module>
Grp = SillyWalk.getGroups(user_id = user)
File "c:\python27\lib\site-packages\SillyWalkapi-1.4.2-py2.7.egg\SillyWalkapi\__init__.py", line 349, in handler
parse_format=args['format'], **args)
File "c:\python27\lib\site-packages\SillyWalkapi-1.4.2-py2.7.egg\SillyWalkapi\__init__.py", line 435, in __wrap_in_parser
return parser(self, data)
File "c:\python27\lib\site-packages\SillyWalkapi-1.4.2-py2.7.egg\SillyWalkapi\__init__.py", line 278, in parse_etree
raise SillyWalkError(u'Error: %(code)s: %(msg)s' % err.attrib)
SillyWalkError: Error: 1: User not found
我試圖把一個try ... except
聲明來解決這個問題:
try:
Grp = SillyWalk.getGroups(user_id = user)
g = 0
for group in Grp.find('groups').findall('group'):
g += 1
u_ID = user
g_ID = group.get('_ID')
gName = "" # group.get('name')
HasParrot = group.get('HasParrot')
Priv = group.get('Priv')
Mbr = group.get('members')
threads = group.get('threads')
tup = '{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\n'.format(u_ID, g_ID, gName.encode('utf-8'), HasParrot, Priv, Mbr, threads)
OutFile.write(tup.encode('utf-8'))
except SillyWalkError:
tup = '{0}\tNo Records Found\n'.format(u_ID)
OutFile.write(tup.encode('utf-8'))
,但它給了我一個未定義的錯誤:
Traceback (most recent call last):
File "C:\Python\API\getgroups.py", line 47, in <module>
except SillyWalkError:
NameError: name 'SillyWalkError' is not defined
>>>
這是我第一次寫的嘗試例外類,所以有人可以告訴我怎麼做?由於各種錯誤原因,SillyWalk.getGroups
有十幾個不同的錯誤編號。我是否需要每個人的情況?
我會永遠在你的債務! (你永遠不會收集我的任何東西,但我仍然欠你的東西!)
順便說一句:雖然生根在我的腳本的膽量,有人可以告訴我如何解決我的gName
問題,所以我不需要將它清空?它不斷給我:
Traceback (most recent call last):
File "C:\Python\API\getgroups.py", line 44, in <module>
OutFile.write(tup.encode('utf-8'))
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 54: ordinal not in range(128)
你可能要將此分成幾個問題 –
更改'除了SillyWalkError:''到除了SillyWalk.SillyWalkError:'因爲該名稱已在該模塊的命名空間中定義。 – martineau
@martineau:除'SillyWalk.SillyWalkError:'我擺脫了「undefined」錯誤,但是我得到了'File「c:\ python27 \ lib \ site-packages \ SillyWalkapi-1.4.2-py2.7。蛋\ SillyWalkapi \ __ init__.py」,線路278,在parse_etree 提高SillyWalkError(u'Error:%(代碼)S:%(MSG)S'%err.attrib)'錯誤 –