在这里,我们将变量传递给给定的异常。我们正在定义一个自定义异常ExampleException,它是Exception基类的子类,并且还定义了__init__方法。我们使用try-except块引发异常,并将变量传递给异常,如下所示。
class ExampleException(Exception):
def __init__(self, foo):
self.foo = foo
try:
raise ExampleException("Bar!")
except ExampleException as e:
print e.foo输出结果
"C:/Users/nhooo1/~bar.py" Bar!