所以假设我有一些引发任何类型或错误的代码。我希望我的代码代替引发AssertionError,但打印出原始错误打印的原始消息。我该怎么办?
(例)
原始错误:'str'和'int'实例之间不支持TypeError:'>'
自定义错误:AssertionError:exception = TypeError:在'str'和'int'的实例之间不支持'>'
你必须抓住引发的异常,然后提出你想要的任何类型。既然你提到要捕获任何类型的错误,你必须使用Exception
类作为你的捕获。
但是,我会注意到这通常是不好的做法,因为您通常只想捕获您预期的特定错误。但是,如果你最终还是犯了一个错误,我认为它并不可怕。但也让我想知道这段代码的目标是什么。无论如何..
抓住什么
try...except Exception as e
提出首选错误
raise AssertionError()
得到消息
e.message
得到的类型
type(e)
把它们放在一起:
try:
# some code that raises an error
g = 10 + '11'
except Exception as e:
raise AssertionError('{}: {}'.format(type(e), e.message))
输出将是:
<type 'exceptions.TypeError'>: unsupported operand type(s) for +: 'int' and 'str'
这可以被清除以摆脱type(e)
的丑陋输出,但一般来说这是你将如何包括错误类型以及相应的消息。
您正在寻找from
syntax(在Python 3中引入),它允许您围绕基本异常包装特定于应用程序的异常。这是一个例子:
>>> try:
... 1 > '1'
... except TypeError as e:
... raise AssertionError() from e
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
TypeError: '>' not supported between instances of 'int' and 'str'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
AssertionError
创建新异常时,可以提供包含诊断消息的字符串。最好定义自己的特定于应用程序的异常,而不是回收AssertionError。如果您定义了几个,请将其中一个作为[grand]父级,并从该祖先继承其他异常。这允许呼叫者方便地捕获细粒度或粗粒度的错误类别。
有一个PEP描述了进一步的考虑因素。
您还可以通过设置__suppress_context__ = True
隐藏原始回溯并进行一些格式化以满足您对预期输出的需求:
try:
a = '1' > 1
except Exception as exc:
assertion_exc = AssertionError('exception = {}: {}'.format(type(exc).__name__, str(exc)))
assertion_exc.__suppress_context__ = True # comment this line to see full traceback
raise assertion_exc
全输出:
Traceback (most recent call last):
File "./file.py", line 8, in <module>
raise assertion_exc
AssertionError: exception = TypeError: '>' not supported between instances of 'str' and 'int'