不确定为什么pythontryexcept不起作用

不确定为什么pythontryexcept不起作用,python,python-2.7,unicode,try-catch,python-unicode,Python,Python 2.7,Unicode,Try Catch,Python Unicode,我的Python程序出现了一个UnicodeDecodeError,所以我想我可以在代码中使用try-except来绕过它。然而,即使使用try-except,我仍然会得到UnicodeDecodeError,而我的程序只是拒绝运行。我是否使用了try-except错误 这是我的密码: combinedCorpus=[] line = text.readline().lower() words_filtered = [word for word in line.split() if len(wo

我的Python程序出现了一个
UnicodeDecodeError
,所以我想我可以在代码中使用try-except来绕过它。然而,即使使用try-except,我仍然会得到
UnicodeDecodeError
,而我的程序只是拒绝运行。我是否使用了try-except错误

这是我的密码:

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."
这是我的回溯:

    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
回溯(最近一次呼叫最后一次):
文件“C:\Users\??\Desktop\python\App.py”,第38行,在
打印json.dumps(组合语料库,缩进=2)
文件“C:\Python27\lib\json\\ uuuuu init\uuuuu.py”,第250行,转储
排序键=排序键,**千瓦)。编码(obj)
文件“C:\Python27\lib\json\encoder.py”,第209行,在encode中
块=列表(块)
文件“C:\Python27\lib\json\encoder.py”,第431行,在iterencode中
对于_iterencode_列表中的块(o,_当前_缩进_级别):
文件“C:\Python27\lib\json\encoder.py”,第332行,在iterencode列表中
对于块中的块:
文件“C:\Python27\lib\json\encoder.py”,第332行,在iterencode列表中
对于块中的块:
文件“C:\Python27\lib\json\encoder.py”,第313行,在iterencode列表中
产量buf+_编码器(值)
UnicodeDecodeError:“utf8”编解码器无法解码位置4-5中的字节:无效的连续字节

注意,异常逐级抛出,我假设程序抛出的异常不是
UnicodeDecodeError
。如果您尝试顶级异常,它应该是
异常
,那么它应该可以正常工作

如下图所示:

try:
    combinedCorpus.append((words_filtered, "positive"))
except Exception as e:
    print "Error appending to combinedCorpus."

如果这样做有效,您应该尝试找出真正的异常是什么,并尝试捕获该异常。

我找到了问题的解决方案。unicode错误实际上来自代码的后面部分

combinedCorpus.append((words_filtered, "positive"))

print json.dumps(combinedCorpus,indent=2)
显然,json.dumps与我的文本不兼容。嗯


感谢所有回答和评论的人

异常的完整回溯是什么?您正确地使用了
try
,但您对引发异常的假设是错误的。我在这段代码中没有看到任何会引发该异常的内容。我添加了回溯,Martijn!如果OP在错误的位置捕捉到一个覆盖异常,希望这个帮助不会有帮助。除了玩Pokomon错误处理是个坏主意外,一般来说,我知道你想说什么,但这仍然不是个好主意。OP应该发布他们真正的回溯,我们可以提供适当的帮助;它缺乏足够的信息来诊断问题。你希望我不要在评论中解释我自己吗?