Method Call in Exception

Carl Banks invalidemail at aerojockey.com
Wed Apr 19 21:55:49 EDT 2006


mwt wrote:
> In my latest attempt at some Python code, I've been tempted to write
> something in the form of:
>
> try:
>     [...] #doing some internet stuff
> except IOError:
>     alternate_method_that_doesnt_need_internet()
>
> This works when I try it, but I feel vaguely uneasy about putting
> method calls in exception blocks. So tell me, Brave Pythoneers, is this
> evil sorcery that I will end up regretting, or is it just plain good
> ol' Python magic?

It's ok.  In fact a lot of Pythonistas recommend this way over the
alternative, even when you don't have to.  For example, a lot of people
recommend this:

try:
    name = record.name
except AttributeError:
    name = "Freddy"

instead of this:

if hasattr(record,"name"):
    name = record.name
else:
    name = "Freddy"

I prefer the latter most of the time; however, sometimes (as it appears
in your case) simply trying it and doing something else if it raises an
exception is easier, more straightforward, and more robust than
explicitly testing the condition.  One thing to consider is whether
something you don't expect could throw the same exception; might have
to disambiguate them somehow in the except block.

Language-wise, I doubt there are any serious gotchas whem running
regular (as opposed to error handling) code in an except block.  So go
right ahead; no need to feel guilty about it.


Carl Banks




More information about the Python-list mailing list