在 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP