are variables local only to try/except blocks?

B

BarrySearle

# Is this valid (or is excp local to try/except)?
try:
try:
doSomething1
excp = 0
except:
excp = 1
#endTry
if (_excp_): doSomething1 # is excp defined here?
excp = 0
except:
excp = 1
#endTry
if (excp): doSomething2 # is excp defined here?


# valid, but more verbose (and maybe redundant?)
excp = 0
try:
excp = 0
try:
doSomething1
excp = 0 # reset incase future inner block
except:
excp = 1
#endTry
if (_excp_): doSomething1
excp = 0 # reset incase inner block set excp=1
except:
excp = 1
#endTry
if (excp): doSomething2

I am not so interested in what a particular version of the
Python/Jython interpreter does, but rather what is "right".

Pls "CC" replies to (e-mail address removed) (as well as newsgroup)
Barry Searle, (e-mail address removed)
 
F

Fredrik Lundh

BarrySearle said:
# Is this valid
yes.

(or is excp local to try/except)?

no. try/except doesn't introduce a new scope.
try:
try:
doSomething1
excp = 0
except:
excp = 1
#endTry
if (_excp_): doSomething1 # is excp defined here?

yes (but _excp_ isn't defined, so you need to change that if-statement)
excp = 0
except:
excp = 1
#endTry
if (excp): doSomething2 # is excp defined here?

yes.

</F>
 
S

Steve Holden

BarrySearle said:
# Is this valid (or is excp local to try/except)?
try:
try:
doSomething1
excp = 0

This block is problematic because excp won;t be set if doSomething1
raises an exception.
except:
excp = 1
#endTry
if (_excp_): doSomething1 # is excp defined here?

Presumably you are expecting doSomething1 to fail or succeed in some
non-deterministic way? Otherwise this will just raise the same exception
again!
excp = 0
except:
excp = 1
#endTry
if (excp): doSomething2 # is excp defined here?


# valid, but more verbose (and maybe redundant?)
excp = 0
try:
excp = 0
try:
doSomething1
excp = 0 # reset incase future inner block
except:
excp = 1
#endTry
if (_excp_): doSomething1
excp = 0 # reset incase inner block set excp=1
except:
excp = 1
#endTry
if (excp): doSomething2

I am not so interested in what a particular version of the
Python/Jython interpreter does, but rather what is "right".

Pls "CC" replies to (e-mail address removed) (as well as newsgroup)
Barry Searle, (e-mail address removed)
Your approach to exception handling is a little simplistic, resulting on
code that reads about as well as a plate of spaghetti.

What are you actually trying to *do*? What problem do you need to solve?

regards
Steve
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top