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

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

在给定的代码中,创建了一个名为FooException的自定义异常,它是超类Exception的子类。我们将字符串对象传递给自定义异常,如下所示:

阅读更多:Python 教程

示例:

#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 '出错了'
else:
print type(bar)
print bar

如果在终端上运行此脚本,则会得到以下结果:

$ python foobar.py

如果我们输入一个字符串,结果如下:

输出:

"C:/Users/TutorialsPoint1/~foobar.py"
输入一个字符串:'voila'
<type 'str'>
Voila

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程