472,371 Members | 1,480 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

When is bare except: justified?

Bare "except:", with no exception specified, is nasty because it can
easily hide bugs.

There is a case where it seemed useful to me in the past. Now it
seems like a bad idea to me (but I think I might still be confused
about it, hence this post). It's this: When you're processing a input
from a file-like object connected to an external source like a network
connection, disk file etc, you have to expect broken, and often
malicious, data (especially from data that arrived from the internet,
of course). except: seemed to me like a good way of dealing with data
that tripped up tacit assumptions in my code about the data.

First example: I have a method that reads cookie data from an HTTP
response and processes it. If the data is malformed in a way I didn't
anticipate, it seems like it would be nice if the code ignored it
rather than crashing the application using my library, or forcing the
application to halt all processing just because of one little bit of
bad data. Still, if you take the attitude that malformed data should
be explicitly detected by the code (whether by catching an exception
or doing a direct "look before you leap" test), rather than relying on
unexpected exceptions, this technique could be seen as hiding a bug
every time it successfully does its job! So I suppose I should just
let the exception propagate, regard any exceptions that show up as
bugs, and fix them. It is of course often useful to let exceptions do
the work, reducing lines of code and avoiding race conditions by not
explicitly checking things. But, even when faced with malicious
network data, I suppose that's only justified when you understand with
reasonable specificity which exceptions are going to be raised and for
what reason -- and my use of except: definitely does not fall into
that category.

Even more doubtfully, I have a pair of methods .save() and .load().
..save() is straightforward: it writes the object's state to a disk
file. .load() loads new data from a disk file, *appending* to the
data held by the object. .load() is supposed to raise IOError when
something goes wrong (IOError is probably the wrong class here, but
that's another issue). .load() makes sure it only raises that error
by catching everything then re-raising IOError: I do this like so:

raise IOError("invalid file format")

def reraise_unmasked_exceptions(unmasked=()):
# There are a few catch-all except: statements in this module, for
# catching input that's bad in unexpected ways.
# This function re-raises some exceptions we don't want to trap.
unmasked = unmasked + (KeyboardInterrupt, SystemExit)
etype = sys.exc_info()[0]
if issubclass(etype, unmasked):

The network data case uses the same function, but like so:

cookies = self.parse_cookies()
cookies = []


0. It's ugly and hard to understand.
1. May mask bugs.
2. Even when bugs are not masked, it won't be obvious what happened
without turning on the debug switch.
Part of the reason it's supposed to only raise that error is that
..revert() is used to to *overwrite* (not append) to the data held by
the objecct, implemented something like this:

def revert(self, filename):
old_state = copy.deepcopy(self.cookies)
self.cookies = {}
except IOError:
self.cookies = old_state

But of course the bare except: could equally well be in .revert(), not
..load(). And really, I now think it shouldn't be there at all,
because it can only hide bugs. Right?

When *is* it justified to use except:, then?

I've seen simple uses like this that seem fine (this one from Alex
Martelli, I think):

def isstringlike(x):
try: x+""
except: return False
else: return True
That's fine because x+"" is too simple to have a bug in it. Even
there, though, what happens if KeyboardInterrupt happens just as the
try block is getting executed?

Another reasonable use, in a straightforward debugging hack:

# use traceback module here to print out some detail of the exception

print "your plugin is buggy"
Anywhere else?
Jul 18 '05 #1
0 1442

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

Similar topics

by: Phil Lee | last post by:
What's the general opinion on which of these to choose? I see that the SoapDocumentServiceAttribute defaults to literal/wrapped, but this article -...
by: =?iso-8859-1?q?Jean-Fran=E7ois_Michaud?= | last post by:
Hello, I was wondering whether it was possible to have left justified or center justified text under XSL:FO. From what I can see, it looks like text-align can take on the values of "left,...
by: trbosjek | last post by:
A total newbie. This simple example below prints left justified. How do I make it right justified, as a number should be? It works for smaller integers (other than unsigned long long). #include...
by: geoffbache | last post by:
Hi all, I find that I semi-frequently get the cryptic message import site failed; use -v for traceback printed on standard error when an arbitrary python script receives SIGINT while the...
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was proposed, which integrated multiple engines and...
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

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.