473,396 Members | 2,011 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,396 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:

try:
self.load_data()
except:
reraise_unmasked_exceptions((IOError,))
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.
if ClientCookie.CLIENTCOOKIE_DEBUG:
raise
unmasked = unmasked + (KeyboardInterrupt, SystemExit)
etype = sys.exc_info()[0]
if issubclass(etype, unmasked):
raise

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

try:
cookies = self.parse_cookies()
except:
reraise_unmasked_exceptions()
cookies = []

Problems:

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 = {}
try:
self.load(filename)
except IOError:
self.cookies = old_state
raise

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:

try:
...
except:
# use traceback module here to print out some detail of the exception
...
raise
And:

try:
use_dodgy_plugin_code()
except:
print "your plugin is buggy"
Anywhere else?
John
Jul 18 '05 #1
0 1519

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

Similar topics

2
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 -...
0
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,...
8
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...
6
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...
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
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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,...
0
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...
0
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...
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
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.