Any way to turn off exception handling? (debugging)

Duncan Booth duncan.booth at invalid.invalid
Fri Feb 12 07:10:26 EST 2010


Peter Otten <__peter__ at web.de> wrote:

> You could try to shadow the exception class with None:
> 
>>>> ZeroDivisionError = None
>>>> try:
> ...     1/0
> ... except ZeroDivisionError:
> ...     print "caught"
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 2, in <module>
> ZeroDivisionError: integer division or modulo by zero
> 

This works in Python 2.x but will break in Python 3. None is not a valid 
exception specification and Python 3 will check for that and complain.

>>> ZeroDivisionError = None
>>> try:
...     1/0
... except ZeroDivisionError:
...     print('caught')
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: int division or modulo by zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: catching classes that do not inherit from BaseException is 
not allowed
>>>

A better solution is to use an empty tuple as that is a valid exception 
specification so will work in both Python 2.x and 3.x:

>>> ZeroDivisionError = ()
>>> try:
...     1/0
... except ZeroDivisionError:
...     print('caught')
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: int division or modulo by zero


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list