Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested exceptions?

Tags:

python

Will this work?

try:
    try:
        field.value = filter(field.value, fields=self.fields, form=self, field=field)
    except TypeError:
        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?

like image 330
mpen Avatar asked Jul 08 '10 22:07

mpen


People also ask

What is nested exception in Python?

The following steps demonstrate how this sort of code might work.</p>","description":"<p>Sometimes you need to place one exception-handling routine within another in a process called <i>nesting.</i> When you nest exception-handling routines, Python tries to find an exception handler in the nested level first and then ...

What are the three types of exceptions?

There are three types of exception—the checked exception, the error and the runtime exception.

What are the two types of exceptions?

There are mainly two types of exceptions in Java as follows: Checked exception. Unchecked exception.


1 Answers

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!'
like image 58
Brent Writes Code Avatar answered Sep 20 '22 14:09

Brent Writes Code