开发者

Nested exceptions?

Will this work?

try:
    try:
        field.value = filter(field.value, fields=self.fields, form=self, field=field)
    except T开发者_开发问答ypeError:
        field.value = filter(field.value)
except ValidationError, e:
    field.errors += e.args
    field.value = revert
    valid = False
    break              

Namely, if that first line throws a ValidationError, will the second except catch it?

I would have written it un-nested, but the second filter statement can fail too! And I want to use the same ValidationError block to catch that as well.

I'd test it myself, but this code is so interwoven now it's difficult to trip it properly :)

As a side note, is it bad to rely on it catching the TypeError and passing in only one arg instead? i.e., deliberately omitting some arguments where they aren't needed?


If the filter statement in the inner try raises an exception, it will first get checked against the inner set of "except" statements and then if none of those catch it, it will be checked against the outer set of "except" statements.

You can convince yourself this is the case just by doing something simple like this (this will only print "Caught the value error"):

try:
    try:
        raise ValueError('1')
    except TypeError:
        print 'Caught the type error'
except ValueError:
    print 'Caught the value error!'

As another example, this one should print "Caught the inner ValueError" only:

try:
    try:
        raise ValueError('1')
    except TypeError:
        pass
    except ValueError:
        print 'Caught the inner ValueError!'
except ValueError:
    print 'Caught the outer value error!'


To compliment Brent's answer, and test the other case:

class ValidationError(Exception): pass
def f(a): raise ValidationError()

try:
    try:
        f()
    except TypeError:
        f(1)
except ValidationError:
    print 'caught1'

try:
    try:
        f(1)
    except TypeError:
        print 'oops'
except ValidationError:
    print 'caught2'

Which prints:

caught1
caught2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜