使用修改后的消息重新引发异常 [英] Re-raising exceptions with modified message
问题描述
使用消息
补充其他信息(例如
模板中的行号)重新提出任何异常的最佳方法是什么?让我们说,为了简单起见,我只想添加对不起。每个
异常消息。我天真的解决方案是:
试试:
...
除了例外,e:
提高e .__ class__,str(e)+"抱歉!"
这对大多数例外非常有效,例如
What is the best way to re-raise any exception with a message
supplemented with additional information (e.g. line number in a
template)? Let''s say for simplicity I just want to add "sorry" to every
exception message. My naive solution was this:
try:
...
except Exception, e:
raise e.__class__, str(e) + ", sorry!"
This works pretty well for most exceptions, e.g.
>> try:
>>try:
.... 1/0
....除了例外,e:
....提高e .__ class__,str(e)+"对不起!"
....
回溯(最近一次调用最后一次):
文件"< stdin>" ,第4行,在< module>
ZeroDivisionError:整数除法或模数为零,抱歉!
但是对于一些无法实例化的异常,它失败了使用
单字符串参数,例如UnicodeDecodeError,它将转换
转换为TypeError:
.... 1/0
.... except Exception, e:
.... raise e.__class__, str(e) + ", sorry!"
....
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ZeroDivisionError: integer division or modulo by zero, sorry!
But it fails for some exceptions that cannot be instantiated with a
single string argument, like UnicodeDecodeError which gets "converted"
to a TypeError:
>>尝试:
>>try:
.... unicode (''\ xe4'')
....除了例外,e:
....提高e .__ class__,str(e)+"对不起!"
....
回溯(最近一次调用最后一次):
文件"< stdin>" ,第4行,在< module>
TypeError:函数需要5个参数(给定1个)
另一种方法是使用包装器Extension类:
类SorryEx(例外):
def __init __(self,e):
self._e = e
def __getattr __(自我,姓名):
返回getattr(self._e,姓名)
def __str __(自我):
return str(self._e)+",抱歉!"
试试:
unicode(''\ xe4'')
除了Exception,e:
raise SorryEx(e)
但是我得到了包装类的名称消息:
__main __。抱歉:''ascii''编解码器无法解码位置0的字节0xe4:
序号不在范围内(128)抱歉!
另一种方法是替换e的__str__方法,但
这对新的样式异常(Python 2.5)不起作用。
有什么建议吗?
- 克里斯
.... unicode(''\xe4'')
.... except Exception, e:
.... raise e.__class__, str(e) + ", sorry!"
....
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: function takes exactly 5 arguments (1 given)
Another approach is using a wrapper Extension class:
class SorryEx(Exception):
def __init__(self, e):
self._e = e
def __getattr__(self, name):
return getattr(self._e, name)
def __str__(self):
return str(self._e) + ", sorry!"
try:
unicode(''\xe4'')
except Exception, e:
raise SorryEx(e)
But then I get the name of the wrapper class in the message:
__main__.SorryEx: ''ascii'' codec can''t decode byte 0xe4 in position 0:
ordinal not in range(128), sorry!
Yet another approach would be to replace the __str__ method of e, but
this does not work for new style Exceptions (Python 2.5).
Any suggestions?
-- Chris
推荐答案
Christoph Zwerschke schrieb:
Christoph Zwerschke schrieb:
使用消息重新提出任何异常的最佳方法
补充了其他信息(例如
模板中的行号)?
What is the best way to re-raise any exception with a message
supplemented with additional information (e.g. line number in a
template)?
我的印象是你不想改变例外,而不是想要以自定义的方式打印回溯。但我可能错了......
Thomas
I have the impression that you do NOT want to change the exceptions,
instead you want to print the traceback in a customized way. But I may be wrong...
Thomas
Thomas Heller写道:
Thomas Heller wrote:
我的印象是你不想改变异常,而是想要以自定义的方式打印回溯。但我可能错了...
I have the impression that you do NOT want to change the exceptions,
instead you want to print the traceback in a customized way. But I may be wrong...
不,我真的想修改这个例外,补充它的消息
以及关于程序的状态。
用例是编译的孩子模板( http://kid-templating.org)。如果
发生错误,我想添加XML
文件的相应行号作为模板开发人员的信息。由于最终错误
处理可能发生在其他地方(例如通过TurboGears导入Kid
模板),我不想修改trackeback处理或其他什么。
- Chris
No, I really want to modify the exception, supplementing its message
with additional information about the state of the program.
The use case are compiled Kid templates (http://kid-templating.org). If
an error occurs, I want to add the corresponding line number of the XML
file as information for the template developer. Since the final error
handling may happen somewhere else (e.g. by TurboGears importing a Kid
template), I do not want to modify trackeback handling or something.
-- Chris
7月5日下午3:53,Christoph Zwerschke< c ... @ online.dewrote:
On Jul 5, 3:53 pm, Christoph Zwerschke <c...@online.dewrote:
用一条消息重新提出任何异常的最佳方法是什么?
补充了额外的信息(例如
中的行号)
模板)?让我们说,为了简单起见,我只想添加对不起。每个
异常消息。我天真的解决方案是:
试试:
...
除了例外,e:
提高e .__ class__,str(e)+"抱歉!"
这对大多数例外非常有效,例如
What is the best way to re-raise any exception with a message
supplemented with additional information (e.g. line number in a
template)? Let''s say for simplicity I just want to add "sorry" to every
exception message. My naive solution was this:
try:
...
except Exception, e:
raise e.__class__, str(e) + ", sorry!"
This works pretty well for most exceptions, e.g.
>>尝试:
>>try:
... 1/0
...除了例外,e:
...提高e .__ class__,str(e)+"抱歉!"
.. 。
回溯(最近一次调用最后一次):
文件"< stdin>",第4行,< module>
ZeroDivisionError:整数除法或模数为零,抱歉!
但是对于某些无法使用
单字符串参数实例化的异常(如UnicodeDecodeError)失败得到转换
到TypeError:
... 1/0
... except Exception, e:
... raise e.__class__, str(e) + ", sorry!"
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
ZeroDivisionError: integer division or modulo by zero, sorry!
But it fails for some exceptions that cannot be instantiated with a
single string argument, like UnicodeDecodeError which gets "converted"
to a TypeError:
>>尝试:
>>try:
... unicode(''\ xe4'')
...除了Exception,e:
...提高e .__ class__,str(e)+"抱歉!"
...
追溯(最近一次调用最后一次):
文件"< stdin>",第4行,在< module>中
TypeError:函数只需要5个参数(给定1个)
另一种方法是使用包装器扩展类:
类SorryEx(例外):
def __init __(self,e):
self._e = e
def __getattr __(自我,姓名):
返回getattr(self._e,姓名)
def __str __(自我):
返回str(self._e)+",对不起!"
尝试:
unicode(''\ xe4'')
除了Exception,e:
加注SorryEx(e)
然后我在消息中得到包装类的名称:
__main __。Sor ryEx:''ascii''编解码器无法解码位置0的字节0xe4:
序数不在范围内(128),对不起!
然而另一种方法是替换e的__str__方法,但是
这对新的样式异常(Python 2.5)不起作用。
有什么建议吗? br />
- Chris
... unicode(''\xe4'')
... except Exception, e:
... raise e.__class__, str(e) + ", sorry!"
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
TypeError: function takes exactly 5 arguments (1 given)
Another approach is using a wrapper Extension class:
class SorryEx(Exception):
def __init__(self, e):
self._e = e
def __getattr__(self, name):
return getattr(self._e, name)
def __str__(self):
return str(self._e) + ", sorry!"
try:
unicode(''\xe4'')
except Exception, e:
raise SorryEx(e)
But then I get the name of the wrapper class in the message:
__main__.SorryEx: ''ascii'' codec can''t decode byte 0xe4 in position 0:
ordinal not in range(128), sorry!
Yet another approach would be to replace the __str__ method of e, but
this does not work for new style Exceptions (Python 2.5).
Any suggestions?
-- Chris
如果你确定异常没有在另一个层面上被抓住,那么
使用以下showtraceback()函数,稍微操纵它的输出
并使用sys.exit终止你的程序
def showtraceback():
'''''
(从code.py复制)
''''''>
尝试:
类型,值,tb = sys.exc_info()
sys.last_type = type
sys.last_value =值
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist [:1]
lst = traceback.format_list(tblist)
if lst:
lst.insert(0," Traceback(最近一次调用最后一次):\ n")
lst [len(lst) ):] = traceback.format_exception_only(类型,
值)
最后:
tblist = tb =无
sys.stderr.write("" .join(lst))
If you are sure that the exception isn''t caught on another level just
use the following showtraceback() function, manipulate it''s output
slightly and terminate your program with sys.exit()
def showtraceback():
''''''
(Copied from code.py)
''''''
try:
type, value, tb = sys.exc_info()
sys.last_type = type
sys.last_value = value
sys.last_traceback = tb
tblist = traceback.extract_tb(tb)
del tblist[:1]
lst = traceback.format_list(tblist)
if lst:
lst.insert(0, "Traceback (most recent call last):\n")
lst[len(lst):] = traceback.format_exception_only(type,
value)
finally:
tblist = tb = None
sys.stderr.write("".join(lst))
这篇关于使用修改后的消息重新引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!