如何在Python中捕获所有旧式类异常?

6
在一个代码中,存在不同的旧式类(如下所示):
class customException: pass

异常会以这种方式被引发:

raise customException()

是否有一种类型可以捕获所有旧式类异常?就像这样:

try:
    ...
except EXCEPTION_TYPE as e:
    #do something with e

或者至少有没有一种方法可以捕获所有(旧式和新式)并将异常对象存储在变量中?

try:
    ...
except:
    #this catches everything but there is no exception variable 

相关链接:http://python3porting.com/differences.html#except - Ashwini Chaudhary
1个回答

4
我能想到的唯一解决方案是使用sys.exc_info
import sys
try:
    raise customException()
except:
    e = sys.exc_info()[1]
    # handle exception "e" here...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接