Unicode error
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Jul 23 23:09:06 EDT 2010
On Fri, 23 Jul 2010 22:46:46 +0100, Nobody wrote:
> On Fri, 23 Jul 2010 10:42:26 +0000, Steven D'Aprano wrote:
>
>> Don't write bare excepts, always catch the error you want and nothing
>> else.
>
> That advice would make more sense if it was possible to know which
> exceptions could be raised. In practice, that isn't possible, as the
> documentation seldom provides this information. Even for the built-in
> classes, the documentation is weak in this regard; for less important
> modules and third-party libraries, it's entirely absent.
Aside: that's an awfully sweeping generalisation for all third-party
libraries.
Yes, the documentation is sometimes weak, but that doesn't stop you from
being sensible. Catching any exception, no matter what, whether you've
heard of it or seen it before or not, is almost never a good idea. The
two problems with bare excepts are:
* They mask user generated keyboard interrupts, which is rude.
* They hide unexpected errors and disguise them as expected errors.
You want unexpected errors to raise an exception as early as possible,
because they probably indicate a bug in your code, and the earlier you
see the exception, the easier it is to debug.
And even if they don't indicate a bug in your code, but merely an under-
documented function, it's still better to find out what that is rather
than sweep it under the carpet. You will have learned something new ("oh,
the httplib functions can raise socket.error as well can they?") which
makes you a better programmer, you have the opportunity to improve the
documentation, you might want to handle it differently ("should I try
again, or just give up now, or reset the flubbler?").
If you decide to just mask the exception, rather than handle it in some
other way, it is easy enough to add an extra check to the except clause.
--
Steven
More information about the Python-list
mailing list