如何正确传递带有 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