REPOST: Re: try-except-finally question

Peter Hansen peter at engcorp.com
Thu Dec 27 03:06:26 CET 2001


"Igor V. Rafienko" wrote:
> 
>             try:
>                 <begin transaction>
>                 <check external factors>
>                 <for each item in group>
>                     <update item in db>
>                 <commit transaction>
>             except ExternalFactorError:
>                 <log error>
>             except DBError:
>                 <log error>
> 
> I have 2 questions:
> 
> * In the innermost try-except there is a possibility for other
>   exceptions than ExternalFactorError and DBError. How can I catch
>   _all_ other exceptions than these two[*]? I'm not so much interested
>   in error itself, but rather whether it occured. I.e. I'm looking for
>   C++'s "catch (...)" construct in Python.

A simple "except:" will do the trick.  Importing sys
and using sys.exc_info() would let you find the details,
per examples you could find posted in comp.lang.python/
in the mailing list archives.  Remember to follow up with
a "raise" to re-raise the exception, after you've recorded
the fact of its occurrence.

> [*] is there a type that _all_ python object inherit from? (I know
> about exceptions.Exception, but I do not want to rely on whether third
> party modules actually inherit from it)

Nope (although 2.2 adds the new "object" class which moves in
this direction).  But I think it's considered bad form *not* to
derive from exceptions.Exception, and I've read that raising
strings instead of objects may eventually be deprecated.
You could always do "except Exception:" followed by a
totally general "except:" with the latter being considered
a fatal error if you wanted to double-check a 3rd party lib.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com

========= WAS CANCELLED BY =======:
Path: news.sol.net!spool0-nwblwi.newsops.execpc.com!newsfeeds.sol.net!newspump.sol.net!newsfeed.direct.ca!look.ca!newsfeed.dacom.co.kr!feeder.kornet.net!news1.kornet.net!ua4canc3ll3r
From: Peter Hansen <peter at engcorp.com>
Newsgroups: comp.lang.python
Subject: cmsg cancel <3C2A8222.88C383A6 at engcorp.com>
Control: cancel <3C2A8222.88C383A6 at engcorp.com>
Date: Mon, 31 Dec 2001 02:51:25 GMT
Organization: A poorly-installed InterNetNews site
Lines: 2
Message-ID: <cancel.3C2A8222.88C383A6 at engcorp.com>
NNTP-Posting-Host: 211.57.49.2
X-Trace: news2.kornet.net 1009775969 27193 211.57.49.2 (31 Dec 2001 05:19:29 GMT)
X-Complaints-To: usenet at news2.kornet.net
NNTP-Posting-Date: Mon, 31 Dec 2001 05:19:29 +0000 (UTC)
X-No-Archive: yes
X-Unac4ncel: yes
X-Commentary: I love NewsAgent 1.10 and the Sandblaster Cancel Engine Build 74 (19 March 1999)

This message was cancelled from within Mozilla.



More information about the Python-list mailing list