【发布时间】:2012-10-16 21:05:16
【问题描述】:
我尝试在 python 2.7 中定义自己的异常类,派生自 BaseException。
class NestedCommentException(BaseException):
"""
Exception for nested comments
"""
def __init__(self, file_path, list_lines):
self.file_path = file_path
self.list_lines = list_lines
def __repr__(self):
return self.__str__()
def __str__(self):
return 'File {0} contains nested comments at lines {1}'.format(self.file_path, ', '.join(self.list_lines))
但是扔的时候不能打印:raise NestedCommentException(file_path, list_lines)triggers
Traceback (most recent call last):
File "D:\DATA\FP12210\My Documents\Outils\SVN\05_impl\2_tools\svn_tag_setup.py", line 85, in <module>
tag_checks()
File "D:\DATA\FP12210\My Documents\Outils\SVN\05_impl\2_tools\svn_tag_setup.py", line 66, in tag_checks
check_nested_comments(ddl_path)
File "D:\DATA\FP12210\My Documents\Outils\SVN\05_impl\2_tools\svn_tag_setup.py", line 54, in check_nested_comments
raise NestedCommentException(file_path, list_lines)
NestedCommentException: <unprintable NestedCommentException object>
即使我定义了__str__ 和__repr__ 方法,您能否解释一下为什么会发生这种情况?
【问题讨论】:
-
您是否有理由从
BaseException继承而不仅仅是Exception? -
好吧,我首先从
object创建了这个类,我有:TypeError: exceptions must be old-style classes or derived from BaseException, not NestedCommentException。我试图让它源自Exception,同样的行为。 -
Exception派生自BaseException并且应该用于用户定义的异常。 -
也许变量 self.file_path 或 self.list_lines 以某种方式搞砸了。尝试从 str 方法中删除它们,看看会发生什么。
-
使用 raise 的简单测试,那么你在做什么不同呢?你能看到你是如何用什么变量来提高它的吗?
标签: python exception python-2.7