473,605 Members | 2,637 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 18276
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******** *************** ***********@s50 g2000hsb.google groups.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******** *************@1 61.53.160.65...
| André <an***********@ gmail.comwrote in
| news:a9******** *************** ***********@s50 g2000hsb.google groups.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****** *************** *************@s 50g2000hsb.goog legroups.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**********@g mail.comwrote:
On May 21, 4:33 pm, Karlo Lozovina <_karlo_@_mosor .net_wrote:
>André <andre.robe...@ gmail.comwrote
innews:a9913f2 d-0c1a-4492-bf58-5c7
88*******@s50g2 000hsb.googlegr oups.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_r etries, 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_retr ies):
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==50 0
and error.hdrs['Bobo-Exception-Type']=='ConflictErro r'):
timestamp("Conf lict 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(b rowser.submit)
follow_link = retryConflict(b rowser.follow_l ink)

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

resp = browser.open(ur l)
follow_relay()

if "ourloginpa ge" 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(b rowser.response ().read())
err = soup.find('td', 'tdbodywarning' )
sys.exit(''.joi n(err.p.content s).strip())

timestamp(messa ge, name, url)
return resp
Jun 27 '08 #8
alex23 <wu*****@gmail. comwrote in
news:48******** *************** ***********@k10 g2000prm.google groups.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**********@i nvalid.invalidw rote 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

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

Similar topics

8
1730
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 Base_error("An object of incorrect type was given....");
8
2728
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? (ie, forget the finally block and just end the try/catch and put the code after the try/catch block). Or does the "finally" construct add some additional functionality?
11
3472
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
13501
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
23
3058
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 block. But, I prefer to dim them "on the fly" only if needed (save as much resources as possible). A little further... I may wish to create a sqlcommand and datareader object ONLY if certain conditions are met. But, if I want to clean these up in the...
5
3021
by: PasalicZaharije | last post by:
Hallo, few days ago I see ctor like this: Ctor() try : v1(0) { // some code } catch(...) { // some code }
32
6111
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 understand Finally runs whether an error was caught or not, I haven't found a use for finally yet.
4
4653
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
2672
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: std::map<unsigned int, CMap*>::iterator ThisMapIt = World.Maps.find( ThisPlayer.Character.Map ); if ( ThisMapIt != World.Maps.end() )
0
8004
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
7934
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8425
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
6743
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3912
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3958
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2438
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1541
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1271
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.