473,554 Members | 2,152 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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:

self.load_data( )
reraise_unmaske d_exceptions((I OError,))
raise IOError("invali d file format")

def reraise_unmaske d_exceptions(un masked=()):
# 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 + (KeyboardInterr upt, SystemExit)
etype = sys.exc_info()[0]
if issubclass(etyp e, unmasked):

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

cookies = self.parse_cook ies()
reraise_unmaske d_exceptions()
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(s elf.cookies)
self.cookies = {}
self.load(filen ame)
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 KeyboardInterru pt 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

use_dodgy_plugi n_code()
print "your plugin is buggy"
Anywhere else?
Jul 18 '05 #1
0 1533

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 - http://msdn.microsoft.com/msdnmag/issues/05/06/ServiceStation/ - says "it probably makes the most sense to use document/literal/bare". In a BasicProfile1_1 compliant web service should one...
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, center, right, justified". In such a context, how would it be possible to make text left justified. would we have to nest 2 blocks, one center aligned...
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 <stdio.h> int main () { unsigned long long int bigger, smaller; bigger= 18446744073709551615ULL; smaller=4294967296ULL;
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 python interpreter is still firing up. If I use -v for traceback I get something along the lines of
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...
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. ...
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...
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...
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...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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...

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.