如何在 Python 中向异常传递变量?


此示例会将一个变量传递到给定的异常。我们定义自定义异常 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/TutorialsPoint1/~bar.py"
Bar!

更新于:2020 年 2 月 13 日

1000+ 浏览

事业起步

完成课程即可获得认证

开始
广告
© . All rights reserved.