Python:如何捕获异常并继续?

标签 python json exception

Why do you have a list of both numbers and some other kind of object? It seems like you're trying to compensate for a design flaw.

事实上,我希望它以这种方式工作,因为我想保留已经在 J​​sonedData() 中编码的数据,然后我希望 json 模块给我一些方法来插入“原始”项目数据而不是默认值,以便编码的 JsonedData 可以重用。

这是代码,谢谢

import json
import io
class JsonedData():
    def __init__(self, data):
        self.data = data
def main():
    try:
        for chunk in json.JSONEncoder().iterencode([1,2,3,JsonedData(u'4'),5]):
            print chunk
    except TypeError: pass# except come method to make the print continue
    # so that printed data is something like:
    # [1
    # ,2
    # ,3
    # , 
    # ,5]

最佳答案

try/except 放在 json.JSONEncoder().encode(item) 的循环中:

print "[",
lst = [1, 2, 3, JsonedData(u'4'), 5]
for i, item in enumerate(lst):
    try:
        chunk = json.JSONEncoder().encode(item)
    except TypeError: 
        pass
    else:
        print chunk
    finally:
        # dont print the ',' if this is the last item in the lst
        if i + 1 != len(lst):
            print ","
print "]"

关于Python:如何捕获异常并继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801903/

相关文章:

arrays - Swift:检查数组的字典对象类型

ios - 不要停止 XCTAssertThrowsSpecific 上的测试执行

wcf - 使用 WCF 加业务逻辑层场景的异常处理

python - UnboundLocalError : local variable 'e' referenced before assignment

python - cv2.imread 在脚本中失败,而不是在命令行中失败

java - 像在 javascript 中一样在 java 中使用 json

python - 找不到满足 torch>=1.0.0 要求的版本?

iOS,JSON 检查值是否为 false 或字符串

python - 无法将 plotly 导入 Jupyter Notebook

python - doctest 中的链式异常