473,320 Members | 1,868 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,320 software developers and data experts.

if or exception

Hi

Just wondering what is "the right thing to do":

number = 0
if len(list) > 0: number = anotherNumber / len(list)

or

try:
number = anotherNumber / len(list)
except:
number = 0

--
Regards
/Thomas

Jul 18 '05 #1
6 1070
Thomas Lindgaard <th****@it-snedkeren.BLACK_HOLE.dk> wrote in
news:pa****************************@it-snedkeren.BLACK_HOLE.dk:
Hi

Just wondering what is "the right thing to do":

number = 0
if len(list) > 0: number = anotherNumber / len(list)

or

try:
number = anotherNumber / len(list)
except:
number = 0


Your first suggestion may be the right answer in some situations.

Your second suggestion is never the right answer. This on the other, could
be a suitable answer:

try:
number = anotherNumber / len(aList)
except ZeroDivisionError:
number = 0

Don't use a bare except, it will just mask other errors: if you feel that
catching an exception is the way to go, then catch only the exceptions that
you expect. Also, but minor, don't use 'list' as a variable name.

However, it seems to me that I would be unlikely to use either of these. I
can't think of a situation where I would want a value that is either the
result of a division, or 0 if the division failed. It is much more likely
that you want to execute some different code if the list is empty than that
you want a different value.

If you explained what problem you are solving leads to this code then you
might get a more useful suggestion about style.

Jul 18 '05 #2
On Thu, 29 Jul 2004 08:44:26 +0000, Duncan Booth wrote:
number = 0
if len(list) > 0: number = anotherNumber / len(list)

[snip]
Your first suggestion may be the right answer in some situations.

Your second suggestion is never the right answer. This on the other, could
be a suitable answer:

try:
number = anotherNumber / len(aList)
except ZeroDivisionError:
number = 0
Hmm... somehow that ZeroDivisionError got lost in translation... is
_was_ supposed to be there :)
Don't use a bare except, it will just mask other errors: if you feel
that catching an exception is the way to go, then catch only the
exceptions that you expect. Also, but minor, don't use 'list' as a
variable name.
I only used 'list' as a variable name to illustrate the type.
However, it seems to me that I would be unlikely to use either of these.
I can't think of a situation where I would want a value that is either
the result of a division, or 0 if the division failed. It is much more
likely that you want to execute some different code if the list is empty
than that you want a different value.

If you explained what problem you are solving leads to this code then
you might get a more useful suggestion about style.


The situation is this: I am trying to make my web crawler "spread out",
ie. I want it to fetch an equal number of pages from each known host (and
not 8000 pages from one host and 1 page from another host as it does now).
Setting number = 0 on ZeroDivisionError was just the first result that
came to mind... after writing the the pseudo code below I can see that it
should have been something along the lines of number = 42 in stead :)

+--- pseudo code ---
| # hostDict is a dictionary mapping currently known host names to info
| # about the host (ie. time for last visit and number of pages fetched
| # from the host)
|
| class Crawler:
| ...
|
| def startPages(self):
| try:
| avgPagesPerHost = numPagesFetched / len(hostDict)
| except ZeroDivisionError:
| # this will only happen the first time around when no hosts are
| # known
| avgPagesPerHost = 42
|
| while len(queue):
| link = queue.pop()
| host = parseLinkAndExtractHost(link)
|
| # a lot of checks
|
| if hostDict[host]['numPagesFetchedFromHost'] < avgPagesPerHost:
| fetchPage(link)
| else:
| delayPage(link)
+----

If the average number of pages found on a host turns out to be 10, then
something has to be done to make sure that the crawler continues fetching
pages from hosts with more than 10 pages... but that is another problem
entirely :)

--
Regards
/Thomas

Jul 18 '05 #3
On Thu, 29 Jul 2004, Thomas Lindgaard wrote:
Just wondering what is "the right thing to do":

number = 0
if len(list) > 0: number = anotherNumber / len(list)

or

try:
number = anotherNumber / len(list)
except:
number = 0


The first will be faster if you expect len(list) to be zero very often,
whereas the latter will be faster if you expect it to be zero very rarely.

This is because in the normal case, the latter needs no extra code (except
a quick 'setup try block'), whereas the former requires a function call
and a comparison for all cases. In the exceptional case, the latter must
raise an catch an exception, which (I believe) is more expensive than the
check in the former. How much more expensive, I'm not qualified to say ;)

Jul 18 '05 #4
Thomas Lindgaard wrote:

[...]
| def startPages(self):
| try:
| avgPagesPerHost = numPagesFetched / len(hostDict)
| except ZeroDivisionError:
| # this will only happen the first time around when no hosts are
| # known
| avgPagesPerHost = 42


[...]

I'd do it the way you have done, but I wouldn't call it
'avgPagesPerHost', since it's a bit misleading, but something along the
lines of 'perHostLimit'.

I'd write the if/else version as:

if numPagesFetched != 0:
perHostLimit = ...
else:
perHostLimit = 42

But since here the standard case seems to be the first one, I think a
try/except solution is both clearer and more efficient.

--
Ciao,
Matteo
Jul 18 '05 #5
Duncan Booth wrote:
However, it seems to me that I would be unlikely to use either of these. I
can't think of a situation where I would want a value that is either the
result of a division, or 0 if the division failed.
What about code for cos(x)/x? By l'Hôpital's Rule, the
limit as x->0 is 0.

Admittedly practical applications for cos(x)/x aren't
as common as for sin(x)/x. Perhaps evaluating the
derivative of sinc(x) is a better example.

Or one might want code to handle a continued fraction
of the form [1; 2, 1, 0] which should evaluate as 1.5
except for the pesky divide-by-zero error.

The moral of the story: even if you can't think of an
application for something, somebody else might.
It is much more likely
that you want to execute some different code if the list is empty than that
you want a different value.


But the question still remains: is it better to do this:

if myList:
call_standard_code(myList)
else:
call_exceptional_code(myList)

or this:

try:
call_standard_code(myList)
except SomeSortOfExceptionHere:
call_exceptional_code(myList)
The essential question remains: is it better to test
for exceptional cases first or just try it and catch
the exception when it happens?

And the answer is, "It depends."

Apart from issues of aesthetics, it also depends on how
often you expect exceptions to occur, and how much work
is needed to determine whether an error will occur
before hand. If it is easy to check for errors up
front, I'd probably stick with the if form. If it takes
just as much work to determine the existance of the
error condition as it takes to actually perform your
calculation, stick to using the try...except form.

But the only way to know for sure which is quicker is
to write both versions and time them with realistic data.

--
Steven

Jul 18 '05 #6
On Fri, 30 Jul 2004, Steve wrote:
What about code for cos(x)/x? By l'Hôpital's Rule, the
limit as x->0 is 0.


Not to be nitpicky, but isn't l'Hôpital only valid in the case that
lim{x->0+} f(x) = lim{x->0-} f(x); i.e. the function approaches the same
value from the left and from the right? cos(x)/x approaches infinity from
the right, but negative infinity from the left, so I think that means it's
undefined at zero. Feel free to correct me though, it's been a couple of
years since Calc III ;)

Jul 18 '05 #7

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

Similar topics

4
by: Nicolas Fleury | last post by:
Hi, I've made a small utility to re-raise an exception with the same stack as before with additional information in it. Since I want to keep the same exception type and that some types have very...
1
by: Old Wolf | last post by:
1. What is the difference between #include <stdexcept> and #include <exception> ? 2. Is there a list somewhere of what each standard exception is used for? either to throw them, or throw...
11
by: Master of C++ | last post by:
Hi, I am writing a simulation package in C++, and so far I've written about 8000 lines of code and have about 30 classes. I haven't used C++ exceptions so far (for various reasons). The only two...
4
by: maricel | last post by:
I have the following base table structure - DDL: CREATE TABLE "ADMINISTRATOR"."T1" ( "C1" INTEGER NOT NULL ) IN "TEST_TS" ; ALTER TABLE "ADMINISTRATOR"."T1" ADD PRIMARY KEY
44
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level...
40
by: Kevin Yu | last post by:
is it a bad programming design to throw exception in the try block then catch it??
6
by: Vadivel Kumar | last post by:
I've a problem in handling a custom exception The following is my custom exception class: public class AppException : public Exception { public AppException (string message, Exception...
3
by: JohnDeHope3 | last post by:
First let me say that I understand that Asp.Net wraps my exception in an HttpUnhandledException. I have found a lot of discussion about that on the web, which was informative, but not helpful. Let...
7
by: Sek | last post by:
Hi Folks! I was pondering over a code and noticed that exception handlers were present in the private, protected as well as public methods. And, ofcourse, public methods were calling priv/prot...
2
by: Darko Miletic | last post by:
Recently I wrote a dll in c++ and to simplify the distribution I decided to link with multithreaded static library (/MT or /MTd option). In debug everything works fine but in release I get this: ...
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...
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: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
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)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.