在 Python 中传递带有自定义异常的对象的正确方法是什么?


在给出的代码中,创建了一个自定义异常 FooException,它是超类 Exception 的子类。我们将按照以下方式将字符串对象传递给自定义异常

示例

#foobar.py
class FooException(Exception):
def __init__(self, text, *args):
super ( FooException, self ).__init__ ( text, *args )
self.text = text
try:
bar = input("Enter a string:")
if not isinstance(bar, basestring):
raise FooException(bar)
except FooException as r:
print 'there is an error'
else:      
print type(bar)
print bar

如果在终端中运行以下脚本,我们得到

$ python foobar.py

如果我们输入一个字符串,我们得到以下

输出

"C:/Users/TutorialsPoint1/~foobar.py"
Enter a string:'voila'
<type 'str'>
Voila


更新时间: 2020-02-13

235 个浏览

启动您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.