在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("输入一个字符串:")
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/nhooo1/~foobar.py" 输入一个字符串:'voila' <type 'str'> Voila
热门推荐
10 财运虎年祝福语简短语
11 单亲爸爸春节祝福语简短
12 狗狗上厕所训练
13 植物种植祝福语简短
14 翻译考试祝福语朋友简短
15 个人周年庆简短祝福语
16 狗狗怎么训练
17 分别祝福语简短搞笑英文
18 生日广州男生祝福语简短