try -> except -> else -> except?
Python
python at rgbaz.eu
Mon Jul 6 12:02:18 EDT 2009
On 6 jul 2009, at 17:46, David House wrote:
> Hi all,
>
> I'm looking for some structure advice. I'm writing something that
> currently looks like the following:
>
> try:
> <short amount of code that may raise a KeyError>
> except KeyError:
> <error handler>
> else:
> <nontrivial amount of code>
>
> This is working fine. However, I now want to add a call to a function
> in the `else' part that may raise an exception, say a ValueError. So I
> was hoping to do something like the following:
>
> try:
> <short amount of code that may raise a KeyError>
> except KeyError:
> <error handler>
> else:
> <nontrivial amount of code>
> except ValueError:
> <error handler>
>
> However, this isn't allowed in Python.
>
> An obvious way round this is to move the `else' clause into the
> `try', i.e.,
>
> try:
> <short amount of code that may raise a KeyError>
> <nontrivial amount of code>
> except KeyError:
> <error handler>
> except ValueError:
> <error handler>
>
> However, I am loath to do this, for two reasons:
>
> (i) if I modify the <nontrivial amount of code> block at some point in
> the future so that it may raise a KeyError, I have to somehow tell
> this exception from the one that may be generated from the <short
> amount of code that may raise a KeyError> line.
> (ii) it moves the error handler for the <short amount of code that may
> raise a KeyError> bit miles away from the line that might generate the
> error, making it unclear which code the KeyError error handler is an
> error handler for.
>
> What would be the best way to structure this?
>
> --
> -David
>
as far as I know try has no 'else'
it's 'finally'
try:
a
except:
b
except:
c
finally:
d
gr
Arno
More information about the Python-list
mailing list