try..except with empty exceptions

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Apr 11 06:47:54 EDT 2015


On Sat, 11 Apr 2015 06:22 pm, Serhiy Storchaka wrote:

> On 11.04.15 10:11, Steven D'Aprano wrote:
>> Anyway, in modern Python (2.6 onwards), now that string exceptions are
>> gone, you can supply something to catch everything. Or nothing, for that
>> matter:
>>
>> BaseException  # catch everything
> 
> Not everything.
> 
>  >>> class A: pass
> ...
>  >>> try: raise A
> ... except BaseException: pass
> ...
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> __main__.A: <__main__.A instance at 0xb707982c>

Hmmm, I thought that starting from 2.6 exceptions had to inherit from
BaseException. Thanks for the correction.


[steve at ando ~]$ python2.7 -c "class A: pass
raise A()"
Traceback (most recent call last):
  File "<string>", line 2, in <module>
__main__.A: <__main__.A instance at 0xb7ebb1ac>


[steve at ando ~]$ python3.3 -c "class A: pass
raise A()"
Traceback (most recent call last):
  File "<string>", line 2, in <module>
TypeError: exceptions must derive from BaseException


Ahah! So it's 3.x only that catching BaseException should catch everything.

In 2.6, Python stopped supporting string exceptions:

[steve at ando ~]$ python2.6 -c "raise 'spam'"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: exceptions must be old-style classes or derived from
BaseException, not str

(glad that at least I remembered that part correctly!)




-- 
Steven




More information about the Python-list mailing list