在 Python 中,传递带有自定义异常的对象正确的方法是什么?
pythonserver side programmingprogramming更新于 2025/6/25 14:04:17
在给定的代码中,已创建自定义异常 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
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

