Python异常处理 - 避免编写30+ try除了块

时间:2015-06-24 09:02:20

标签: python dictionary exception-handling

我有一个从xml填充的字典。字典有很多键值对。我必须使用该字典中的值填充自定义对象。如果字典中的一个键不存在或者值不是预期的类型,我想捕获异常,记录哪个键并继续执行。有没有比使用try expect块更好的方法来围绕每一行。具体来说,我想避免这种语法,它可以满足我的需求,但我想知道是否有更有效的解决方案:

try:
    my_object.prop1 = dictionary['key1']
except Exception as e:
    log.write('key1')

try:
    my_object.prop2 = dictionary['key2']
except Exception as e:
    log.write('key2')

try:
    my_object.prop3 = dictionary['key3']
except Exception as e:
    log.write('key3')

....

2 个答案:

答案 0 :(得分:4)

以编程方式执行。

public class CanFilterStruct extends Structure implements Structure.ByReference
{
    public int can_id;
    public int can_mask;

    public CanFilterStruct()
    {
        super();
    }

    @Override
    protected List getFieldOrder() 
    {
        return Arrays.asList("can_id", "can_mask");
    }
}

答案 1 :(得分:4)

for key, prop in [('key1', 'prop1'), ('key2', 'prop2'), ('key3', 'prop3')]:
    try:
        setattr(my_object, prop, dictionary[key])
    except KeyError:
        log.write(key)

请注意,我在这里也使用KeyError;尽量保持捕获的异常尽可能具体。如果prop1可能会引发自己的错误,请将其添加到预期错误列表中。