用户定义的例外:<不可打印的...对象> [英] User-defined exception: <unprintable ... object>
问题描述
我尝试在python 2.7中定义自己的异常类,该类源自 BaseException
。
I tried to define my own exception class in python 2.7, deriving from 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)
触发器
But when throwing it, it cannot be printed: 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 __ , code>和
__ repr __
方法?
推荐答案
我的猜测是您在 file_path
或 list_lines
变量中具有unicode,因为没有unicode功能的控制台上不会打印它。
My guess is that you have unicode in file_path
or list_lines
variables dues to which it is not being printed on a console without unicode capabilities.
或 __ str __
中的任何其他异常都可能导致这种奇怪的行为,最好的方法是捕获异常并查看结果碰巧也要使用调试器
or any other exception in __str__
can cause such strange behavior, best way is to catch exception and see whats is happening, use debugger too
def __str__(self):
try:
s = 'File {0} contains nested comments at lines {1}'.format(self.file_path, ', '.join(self.list_lines))
except Exception,e:
print "-----",type(e),e
return s
这篇关于用户定义的例外:<不可打印的...对象>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!