473,287 Members | 1,570 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

Returning to 'try' block after catching an exception

I'm not sure if Python can do this, and I can't find it on the web. So,
here it goes:
try:
some_function()
except SomeException:
some_function2()
some_function3()
...
# somehow goto 'try' block again

In case it's not clear what I meant: after executing some_function()
exception SomeExcpetion gets risen. Then, in except block I do something
to fix whatever is causing the exception and then I would like to go back
to try block, and execute some_function() again. Is that doable?

Thanks.
--
_______ Karlo Lozovina - Mosor
| | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163
| || _ | _ | Parce mihi domine quia Dalmata sum.
|__|_|__||_____|_____|
Jun 27 '08 #1
12 18185
On May 21, 8:13 pm, Karlo Lozovina <_karlo_@_mosor.net_wrote:
I'm not sure if Python can do this, and I can't find it on the web. So,
here it goes:

try:
some_function()
except SomeException:
some_function2()
some_function3()
...
# somehow goto 'try' block again

In case it's not clear what I meant: after executing some_function()
exception SomeExcpetion gets risen. Then, in except block I do something
to fix whatever is causing the exception and then I would like to go back
to try block, and execute some_function() again. Is that doable?
How about something like the following (untested)

done = False
while not done:
try:
some_function()
done = True
except:
some_function2()
some_function3()

André

>
Thanks.

--
_______ Karlo Lozovina - Mosor
| | |.-----.-----. web:http://www.mosor.net|| ICQ#: 10667163
| || _ | _ | Parce mihi domine quia Dalmata sum.
|__|_|__||_____|_____|
Jun 27 '08 #2
André <an***********@gmail.comwrote in
news:a9**********************************@s50g2000 hsb.googlegroups.com:
How about something like the following (untested)

done = False
while not done:
try:
some_function()
done = True
except:
some_function2()
some_function3()
Sure, that works, but I was aiming for something more elegant and Pythonic
;).
--
_______ Karlo Lozovina - Mosor
| | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163
| || _ | _ | Parce mihi domine quia Dalmata sum.
|__|_|__||_____|_____|
Jun 27 '08 #3

"Karlo Lozovina" <_karlo_@_mosor.net_wrote in message
news:Xn*********************@161.53.160.65...
| André <an***********@gmail.comwrote in
| news:a9**********************************@s50g2000 hsb.googlegroups.com:
|
| How about something like the following (untested)
| >
| done = False
| while not done:
| try:
| some_function()
| done = True
| except:
| some_function2()
| some_function3()
|
| Sure, that works, but I was aiming for something more elegant and
Pythonic
| ;).

while True:
try:
some_function()
break
except Exception:
patchup()

???

Jun 27 '08 #4
On May 21, 4:33 pm, Karlo Lozovina <_karlo_@_mosor.net_wrote:
André <andre.robe...@gmail.comwrote innews:a9**********************************@s50g20 00hsb.googlegroups.com:
How about something like the following (untested)
done = False
while not done:
try:
some_function()
done = True
except:
some_function2()
some_function3()

Sure, that works, but I was aiming for something more elegant and Pythonic
;).

--
_______ Karlo Lozovina - Mosor
| | |.-----.-----. web:http://www.mosor.net|| ICQ#: 10667163
| || _ | _ | Parce mihi domine quia Dalmata sum.
|__|_|__||_____|_____|
It's hard to get around a while loop if you want to conditionally
repeat something. There's no built-in way to do what you ask.
Jun 27 '08 #5
On May 22, 9:13 am, Karlo Lozovina <_karlo_@_mosor.net_wrote:
In case it's not clear what I meant: after executing some_function()
exception SomeExcpetion gets risen. Then, in except block I do something
to fix whatever is causing the exception and then I would like to go back
to try block, and execute some_function() again. Is that doable?
If you know what exception to expect, and you know how to "fix" the
cause, why not just put tests _before_ some_function() is called to
ensure that everything is as it needs to be?
Jun 27 '08 #6
alex23 <wu*****@gmail.comwrites:
On May 22, 9:13 am, Karlo Lozovina <_karlo_@_mosor.net_wrote:
In case it's not clear what I meant: after executing
some_function() exception SomeExcpetion gets risen. Then, in
except block I do something to fix whatever is causing the
exception and then I would like to go back to try block, and
execute some_function() again. Is that doable?

If you know what exception to expect, and you know how to "fix" the
cause, why not just put tests _before_ some_function() is called to
ensure that everything is as it needs to be?
This is LBYL ("Look Before You Leap") programming style, and is
contrasted with EAFP ("it is Easier to Ask Forgiveness than
Permission") style.

<URL:http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html>

EAFP is usually considered more Pythonic, and usually results in
smaller, clearer code.

I'm currently undecided in this case whether EAFP is correct — though
I suspect it is, as in most cases. I wanted to address your "why not
LBYL" question though.

--
\ “Courage is not the absence of fear, but the decision that |
`\ something else is more important than fear.” —Ambrose |
_o__) Redmoon |
Ben Finney
Jun 27 '08 #7
bukzor <wo**********@gmail.comwrote:
On May 21, 4:33 pm, Karlo Lozovina <_karlo_@_mosor.net_wrote:
>André <andre.robe...@gmail.comwrote
innews:a9913f2d-0c1a-4492-bf58-5c7
88*******@s50g2000hsb.googlegroups.com:
>>
How about something like the following (untested)
done = False
while not done:
try:
some_function()
done = True
except:
some_function2()
some_function3()

Sure, that works, but I was aiming for something more elegant and
Pythonic
Catching only the specific exceptions you think you can handle would be
more Pythonic: that way things like sys.exit() will still work inside
some_function.
>
It's hard to get around a while loop if you want to conditionally
repeat something. There's no built-in way to do what you ask.
I prefer a 'for' loop rather than 'while' so I can limit the number of
retries.

The following may or may not be 'more pythonic', but is something I've
used. It's a factory to generate decorators which will retry the
decorated function. You have to specify the maximum number of retries,
the exceptions which indicate that it is retryable, and an optional
filter function which can try to do fixups or just specify some
additional conditions to be tested.

class TooManyRetries(Exception):
def __init__(self, inner):
self.inner = inner
def __str__(self):
return 'Too many retries: %s' % (str(self.inner),)

def retryable(max_retries, exceptions, filter=None):
"""Creates a decorator which will retry specific exceptions.
After there have been too many retries it raises TooManyRetries.
"""
def decorator(f):
def wrapper(*args, **kw):
for i in xrange(max_retries):
try:
return f(*args, **kw)
except exceptions, e:
exc_info = sys.exc_info()
# Check for retry even the last time in case the
# filter wants to do any logging.
if filter is not None and filter(e,
i==max_retries-1):
pass
else:
raise
# If we get here we have exceeded the maximum number of
# retries.
raise TooManyRetries, e, exc_info[2]

wrapper.__name__ = f.__name__
return wrapper
return decorator

def isConflictError(error, lasttime):
if (error.code==500
and error.hdrs['Bobo-Exception-Type']=='ConflictError'):
timestamp("Conflict Error", error.filename)
return True
return False

retryConflict = retryable(3, HTTPError, isConflictError)

# ----- some code showing it in use -----------
from mechanize import Browser
browser = Browser()

submit = retryConflict(browser.submit)
follow_link = retryConflict(browser.follow_link)

@retryConflict
def openpage(message, url, name=None):
global PASSWORD
if PASSWORD is None:
start = time.time()
PASSWORD = getpass.getpass()
#PASSWORD = raw_input("password?")
end = time.time()
logger.LASTTIME += end-start # Don't include input in timestamp.

resp = browser.open(url)
follow_relay()

if "ourloginpage" in browser.geturl():
# Not yet logged in
timestamp("Got login form")
browser.select_form(nr=0)
browser["user"] = USERID
browser["pass"] = PASSWORD
resp = browser.submit()
follow_relay()
if 'query' in [f.name for f in browser.forms()]:
if name=="query":
soup = BeautifulSoup(browser.response().read())
err = soup.find('td', 'tdbodywarning')
sys.exit(''.join(err.p.contents).strip())

timestamp(message, name, url)
return resp
Jun 27 '08 #8
alex23 <wu*****@gmail.comwrote in
news:48**********************************@k10g2000 prm.googlegroups.com:
If you know what exception to expect, and you know how to "fix" the
cause, why not just put tests _before_ some_function() is called to
ensure that everything is as it needs to be?
Because when you expect exception to occur on something like 0.01% of
cases, and you have 4 or 5 exceptions and the code to test for each
conditions that cause exceptions is quite long and burried deep inside
some other code it's much better to do it this way ;). Too bad there's no
syntactic sugar for doing this kind of try-except loop.
--
_______ Karlo Lozovina - Mosor
| | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163
| || _ | _ | Parce mihi domine quia Dalmata sum.
|__|_|__||_____|_____|
Jun 27 '08 #9
Duncan Booth <du**********@invalid.invalidwrote in
news:Xn*************************@127.0.0.1:
Catching only the specific exceptions you think you can handle would
be more Pythonic: that way things like sys.exit() will still work
inside some_function.
I know, this was just a somewhat poorly example ;).
I prefer a 'for' loop rather than 'while' so I can limit the number of
retries.

The following may or may not be 'more pythonic', but is something I've
used. It's a factory to generate decorators which will retry the
decorated function. You have to specify the maximum number of retries,
the exceptions which indicate that it is retryable, and an optional
filter function which can try to do fixups or just specify some
additional conditions to be tested.
Interesting approach, I think I'll use something like that for avoding
infinite loops. Thanks a lot...

--
_______ Karlo Lozovina - Mosor
| | |.-----.-----. web: http://www.mosor.net || ICQ#: 10667163
| || _ | _ | Parce mihi domine quia Dalmata sum.
|__|_|__||_____|_____|
Jun 27 '08 #10
On May 22, 6:15 pm, Karlo Lozovina <_karlo_@_mosor.net_wrote:
Because when you expect exception to occur on something like 0.01% of
cases, and you have 4 or 5 exceptions and the code to test for each
conditions that cause exceptions is quite long and burried deep inside
some other code it's much better to do it this way ;). Too bad there's no
syntactic sugar for doing this kind of try-except loop.
I'm surprised your unit tests let it get to such a state... ;)

How about something like this?

retry, total_fail = False, False
try:
some_function()
except SomeException:
some_function2()
some_function3()
retry = True
finally:
if retry:
try:
some_function()
except SomeException:
total_fail = True

Using 'finally' seems more explicit about it being part of the
exception handling than using a loop construct.

Actually, this is even more direct:

try:
some_function()
except SomeException:
some_function2()
some_function3()
try:
some_function()
except SomeException:
raise SomeError
Jun 27 '08 #11
Might have a stack overflow issue, if it retries too many times?

"alex23" <wu*****@gmail.comwrote in message
news:b3**********************************@x1g2000p rh.googlegroups.com...
On May 22, 6:15 pm, Karlo Lozovina <_karlo_@_mosor.net_wrote:
>Because when you expect exception to occur on something like 0.01% of
cases, and you have 4 or 5 exceptions and the code to test for each
conditions that cause exceptions is quite long and burried deep inside
some other code it's much better to do it this way ;). Too bad there's no
syntactic sugar for doing this kind of try-except loop.

I'm surprised your unit tests let it get to such a state... ;)

How about something like this?

retry, total_fail = False, False
try:
some_function()
except SomeException:
some_function2()
some_function3()
retry = True
finally:
if retry:
try:
some_function()
except SomeException:
total_fail = True

Using 'finally' seems more explicit about it being part of the
exception handling than using a loop construct.

Actually, this is even more direct:

try:
some_function()
except SomeException:
some_function2()
some_function3()
try:
some_function()
except SomeException:
raise SomeError

Jun 27 '08 #12
On May 23, 4:01 am, "inhahe" <inh...@gmail.comwrote:
Might have a stack overflow issue, if it retries too many times?
In which example? Neither of them is looping...
Jun 27 '08 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Adam H. Peterson | last post by:
Hello, I sometimes find myself writing code something like this: try { Derived &d=dynamic_cast<Derived&>(b); d.do_something_complicated(); // etc.... } catch (std::bad_cast) { throw...
8
by: Z D | last post by:
Hi, I was wondering what's the point of "finally" is in a try..catch..finally block? Isn't it the same to put the code that would be in the "finally" section right after the try/catch block?...
11
by: Pohihihi | last post by:
I was wondering what is the ill effect of using try catch in the code, both nested and simple big one. e.g. try { \\ whole app code goes here } catch (Exception ee) {}
40
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
23
by: VB Programmer | last post by:
Variable scope doesn't make sense to me when it comes to Try Catch Finally. Example: In order to close/dispose a db connection you have to dim the connection outside of the Try Catch Finally...
5
by: PasalicZaharije | last post by:
Hallo, few days ago I see ctor like this: Ctor() try : v1(0) { // some code } catch(...) { // some code }
32
by: cj | last post by:
Another wish of mine. I wish there was a way in the Try Catch structure to say if there wasn't an error to do something. Like an else statement. Try Catch Else Finally. Also because I...
4
by: garyusenet | last post by:
Hi I'm using the following code which is finally working. Public Class Form1 Shared ActElement As Object Shared ActFields As DataSet Public Sub SetActElement() Dim objApp As New Object
21
by: Jim Langston | last post by:
I'm sure this has been asked a few times, but I'm still not sure. I want to create a function to simplify getting a reference to a CMap in a map. This is what I do now in code: ...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.