[Python-ideas] suggestion for try/except program flow
Nick Coghlan
ncoghlan at gmail.com
Sun Mar 29 01:24:01 CET 2009
Mark Donald wrote:
> Unless something has changed in Python 3+, I believe Nick's idiom
> requires the generic handler code to be copied into a second except
> clause to achieve identical behaviour, as follows...
Guido already said this, but yes, something did change in 3.0: unlike
the 2.x series, the raise statement in 3.x only accepts instances of
BaseException, so having both an "except BaseException:" clause and a
bare "except:" clause becomes redundant.
Running 2.x code with the -3 flag to enable Py3k deprecation warnings
actually points this out whenever a non-instance of BaseException is raised.
'Normal' exceptions are encouraged to inherit from Exception, with only
'terminal' exceptions (currently only SystemExit, GeneratorExit,
KeyboardInterrupt) outside that heirarchy.
I agree that in 2.x, this means that if you want to handle non-Exception
exceptions along with well-behaved exceptions, you need to use
sys.exc_info() to adapt my previous example:
except:
_et, e, _tb = sys.exc_info()
if isinstance(e, Cheese):
# handle cheese
# handle all manner of stuff, including cheese
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
More information about the Python-ideas
mailing list