David House a écrit :
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.

If your error handler terminates the function (which is usually the case when using the else clause), you can just skip the else statement, ie:

try:
    <short amount of code that may raise a KeyError>
except KeyError:
    <error handler with early exit>
<nontrivial amount of code>

Then adding one or more try/except is just trivial.


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.

Nope. But this is legal:


try:
    <short amount of code that may raise a KeyError>
except KeyError:
    <error handler>
else:
    try:
        <nontrivial amount of code>
    except ValueError:
        <error handler>



An obvious way round this is to move the `else' clause into the `try'

"obvious" but not necessarily the best thing to do.

(snip - cf above for simple answers)


--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to