473,890 Members | 1,761 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 18358
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
1740
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
2740
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
3500
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
13560
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
23
3095
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
3036
by: PasalicZaharije | last post by:
Hallo, few days ago I see ctor like this: Ctor() try : v1(0) { // some code } catch(...) { // some code }
32
6149
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
4678
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
2710
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
9976
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
11215
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
10802
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10908
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10451
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9618
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...
1
8008
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6035
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3267
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.