[英]Not sure why Python Try-Except is not working
My Python program has been getting a UnicodeDecodeError
, so I thought I could use try-except in my code to bypass it. 我的Python程序一直在获取UnicodeDecodeError
,所以我认为我可以在代码中使用try-except来绕过它。 However, even with the try-except, I continue to get the UnicodeDecodeError
and my program simply refuses to run. 但是,即使使用了try-except,我仍然会收到UnicodeDecodeError
而我的程序只是拒绝运行。 Am I using try-except wrong? 我是否使用try-except错误?
Here's my code: 这是我的代码:
combinedCorpus=[]
line = text.readline().lower()
words_filtered = [word for word in line.split() if len(word) >= 3]
try:
combinedCorpus.append((words_filtered, "positive")) #this is where my problem is
except UnicodeDecodeError:
print "Error appending to combinedCorpus."
Here is my traceback: 这是我的回溯:
Traceback (most recent call last):
File "C:\Users\???\Desktop\python\App.py", line 38, in <module>
print json.dumps(combinedCorpus,indent=2)
File "C:\Python27\lib\json\__init__.py", line 250, in dumps
sort_keys=sort_keys, **kw).encode(obj)
File "C:\Python27\lib\json\encoder.py", line 209, in encode
chunks = list(chunks)
File "C:\Python27\lib\json\encoder.py", line 431, in _iterencode
for chunk in _iterencode_list(o, _current_indent_level):
File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
for chunk in chunks:
File "C:\Python27\lib\json\encoder.py", line 332, in _iterencode_list
for chunk in chunks:
File "C:\Python27\lib\json\encoder.py", line 313, in _iterencode_list
yield buf + _encoder(value)
UnicodeDecodeError: 'utf8' codec can't decode bytes in position 4-5: invalid continuation byte
I found the solution to my problem. 我找到了解决我问题的方法。 The unicode error actually came from later in the code. unicode错误实际上来自后面的代码。
combinedCorpus.append((words_filtered, "positive"))
print json.dumps(combinedCorpus,indent=2)
Apparently, json.dumps wasn't compatible with my text. 显然,json.dumps与我的文本不兼容。 Huh. 呵呵。
Thanks to everyone who answered and commented! 感谢所有回答和评论的人!
Note that the Exception throws up level by level, I assume that the exception that the program throws out is not UnicodeDecodeError
. 注意,Exception是逐级抛出的,我假设程序抛出的异常不是UnicodeDecodeError
。 If you try the top level exception, which should be Exception
, it should be work. 如果尝试顶级异常(应该为Exception
,则应该可以正常工作。
Like below: 如下所示:
try:
combinedCorpus.append((words_filtered, "positive"))
except Exception as e:
print "Error appending to combinedCorpus."
If this works, you should try to find what the real exception is, and try to catch that one. 如果这行得通,则应尝试找出真正的异常是什么,并尝试捕获该异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.