473,406 Members | 2,312 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,406 software developers and data experts.

Method Call in Exception

mwt
In my latest attempt at some Python code, I've been tempted to write
something in the form of:

try:
[...] #doing some internet stuff
except IOError:
alternate_method_that_doesnt_need_internet()

This works when I try it, but I feel vaguely uneasy about putting
method calls in exception blocks. So tell me, Brave Pythoneers, is this
evil sorcery that I will end up regretting, or is it just plain good
ol' Python magic?

Apr 20 '06 #1
8 1236
Em Qua, 2006-04-19 Ã*s 16:54 -0700, mwt escreveu:
This works when I try it, but I feel vaguely uneasy about putting
method calls in exception blocks.
What do you put in exception blocks?!

So tell me, Brave Pythoneers, is this
evil sorcery that I will end up regretting, or is it just plain good
ol' Python magic?


IMHO, the exception block in Python is used a lot in places where you
could use an if-then-else, like your example that could be written as

if internet_available():
[...] #doing some internet stuff
else:
alternate_method_that_doesnt_need_internet()

So yes, I think there's no problem there.

--
Felipe.

Apr 20 '06 #2
mwt

Felipe Almeida Lessa wrote:
Em Qua, 2006-04-19 às 16:54 -0700, mwt escreveu:
This works when I try it, but I feel vaguely uneasy about putting
method calls in exception blocks.
What do you put in exception blocks?!


Usually I just print an error message.

So tell me, Brave Pythoneers, is this
evil sorcery that I will end up regretting, or is it just plain good
ol' Python magic?


IMHO, the exception block in Python is used a lot in places where you
could use an if-then-else, like your example that could be written as

if internet_available():
[...] #doing some internet stuff
else:
alternate_method_that_doesnt_need_internet()

So yes, I think there's no problem there.


Normally I don't like to use exception blocks to do condition-statement
stuff. At least that is how my Java training has programmed me. But in
this case, the condition is whether the internet connection is working
or not, and I don't see any other way to do it. And furthermore, I
don't know if the exceptions-as-logic is a no-no in Python. Hence the
question.

Apr 20 '06 #3
Felipe Almeida Lessa wrote:
Em Qua, 2006-04-19 às 16:54 -0700, mwt escreveu:
This works when I try it, but I feel vaguely uneasy about putting
method calls in exception blocks.


What do you put in exception blocks?!

So tell me, Brave Pythoneers, is this
evil sorcery that I will end up regretting, or is it just plain good
ol' Python magic?


IMHO, the exception block in Python is used a lot in places where you
could use an if-then-else, like your example that could be written as

if internet_available():
[...] #doing some internet stuff
else:
alternate_method_that_doesnt_need_internet()

So yes, I think there's no problem there.


What if the service is overloaded and always times out? For end user
it's basically the same as there is no internet access. I routinely use
the following pattern:

unrecoverable = MemoryError, IOError
try:
do_your_best()
except unrecoverable, e:
util.help_on_error(e)
sys.exit(1)

def do_your_best():
recoverable = IOError, socket.error, SomeOtherError
try:
do_something()
except recoverable, e:
do_something_else()

Apr 20 '06 #4
mwt wrote:
In my latest attempt at some Python code, I've been tempted to write
something in the form of:

try:
[...] #doing some internet stuff
except IOError:
alternate_method_that_doesnt_need_internet()

This works when I try it, but I feel vaguely uneasy about putting
method calls in exception blocks. So tell me, Brave Pythoneers, is this
evil sorcery that I will end up regretting, or is it just plain good
ol' Python magic?


It's ok. In fact a lot of Pythonistas recommend this way over the
alternative, even when you don't have to. For example, a lot of people
recommend this:

try:
name = record.name
except AttributeError:
name = "Freddy"

instead of this:

if hasattr(record,"name"):
name = record.name
else:
name = "Freddy"

I prefer the latter most of the time; however, sometimes (as it appears
in your case) simply trying it and doing something else if it raises an
exception is easier, more straightforward, and more robust than
explicitly testing the condition. One thing to consider is whether
something you don't expect could throw the same exception; might have
to disambiguate them somehow in the except block.

Language-wise, I doubt there are any serious gotchas whem running
regular (as opposed to error handling) code in an except block. So go
right ahead; no need to feel guilty about it.
Carl Banks

Apr 20 '06 #5
Carl Banks wrote:
In fact a lot of Pythonistas recommend this way over the
alternative, even when you don't have to. For example, a lot of people
recommend this:

try:
name = record.name
except AttributeError:
name = "Freddy"

instead of this:

if hasattr(record,"name"):
name = record.name
else:
name = "Freddy"


In this specific case, either of these would be better written as:

name = getattr(record, 'name', 'Freddy')
Apr 20 '06 #6
mwt wrote:
(snip)
This works when I try it, but I feel vaguely uneasy about putting
method calls in exception blocks.
What do you put in exception blocks?!


Whatever fits the specific case...

(snip) Normally I don't like to use exception blocks to do condition-statement
stuff. At least that is how my Java training has programmed me.
http://dirtsimple.org/2004/12/python-is-not-java.html
But in
this case, the condition is whether the internet connection is working
or not, and I don't see any other way to do it.
As Felipe wrote, you could also use a if/else.

And furthermore, I
don't know if the exceptions-as-logic is a no-no in Python.


It's not.

The main guideline here is that a else/if has a constant cost - the test
is always executed -, while a try/except only adds overhead if it's
fired. So - if you leave out purely stylistic or religious
considerations - the 'good' choice depends mostly on the 'cost of the
test'/'cost of the exception' ratio and the 'have connection'/'no
connection' ratio.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Apr 20 '06 #7

"mwt" <mi*********@gmail.com> wrote in message
news:11*********************@t31g2000cwb.googlegro ups.com...
In my latest attempt at some Python code, I've been tempted to write
something in the form of:

try:
[...] #doing some internet stuff
except IOError:
alternate_method_that_doesnt_need_internet()

I'm only a hack at programming but where I find try: blocks useful is where
I have multiple statements within the try: block, any one or more of which
can produce an exception. I just want to trap a failure and get out of
there. This happens to me for any number of reasons when I drive other apps
through the com interface. (In my job I just write simple apps to make my
job easier, not bomb-proof customer-focused code). So in your case perhaps
you have open connection, find site, get data within the try block, and exit
gracefully if any one fails. How you use it depends on what level of detail
you need.

bwaha

Apr 20 '06 #8
Carl Banks wrote:
mwt wrote:
In my latest attempt at some Python code, I've been tempted to write
something in the form of:

try:
[...] #doing some internet stuff
except IOError:
alternate_method_that_doesnt_need_internet()

This works when I try it, but I feel vaguely uneasy about putting
method calls in exception blocks. So tell me, Brave Pythoneers, is this
evil sorcery that I will end up regretting, or is it just plain good
ol' Python magic?


It's ok. In fact a lot of Pythonistas recommend this way over the
alternative, even when you don't have to. For example, a lot of people
recommend this:

try:
name = record.name
except AttributeError:
name = "Freddy"

instead of this:

if hasattr(record,"name"):
name = record.name
else:
name = "Freddy"


or maybe
name = getattr(record, 'name', 'Freddy')

Kent
Apr 20 '06 #9

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

Similar topics

31
by: Chris S. | last post by:
Is there a purpose for using trailing and leading double underscores for built-in method names? My impression was that underscores are supposed to imply some sort of pseudo-privatization, but would...
9
by: Paul Rubin | last post by:
I'm trying the super() function as described in Python Cookbook, 1st ed, p. 172 (Recipe 5.4). class A(object): def f(self): print 'A' class B(object): def f(self):
14
by: Michael Winter | last post by:
In an attempt to answer another question in this group, I've had to resort to calling the DOM method, Node.removeChild(), using a reference to it (long story...). That is, passing Node.removeChild....
0
by: Mike Schilling | last post by:
I have some code that calls methods reflectively (the method called and its parameters are determined by text received in a SOAP message, and I construct a map from strings to MethodInfos). The...
1
by: Ajay Pal Singh | last post by:
Hi, I am making an windows service similar to windows task schedular. The service would invoke the methods of some assemblies at some predefined schedules. (windows service read the...
1
by: Ryan McLean | last post by:
Hi everyone! What is happening is the method: sub_btnSubmitClicked is being executed every time any other object with a Handler is executed. I am trying not to use the withevents and handles...
5
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS...
3
by: Giovanni Bassi | last post by:
Hello Group, I am running an operation in a different thread. There are resources that are released when the thread is done running. This is done at the end of the execution as it raises an...
6
by: Teresa | last post by:
1) If I do want to keep an object alive throughout the live of an application, how can I ensure that the GC doesn't clean it up? 2a) How do I determine if an object is a managed or an unmanged...
7
by: Peter Laan | last post by:
Is there a simple way to encapsulate the functionality to redo a method call a second time in case a specific exception is thrown? We are sending commands to an external system and if the sessionId...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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,...
0
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...

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.