【发布时间】:2017-02-21 00:48:55
【问题描述】:
再次问候 StackOverflow 社区,
我正在阅读一位同事写的图书馆,发现了一些我不太了解他们想要做什么的东西。但也许这是我在 Python 语法方面缺少的东西。
class SampleClass:
def some_function(self) -> None:
try:
self.do_something()
except CustomException as e:
raise DifferentExceptionClass("Could not do something", e)
# The previous line is the cause of bewilderment.
def do_something(self) -> None:
raise CustomException("Tried to do something and failed.")
我读过 raise 可以接受参数,但这似乎引发了以元组作为值的 DifferentExceptionClass 异常。我的同事在这里所做的与 raise DifferentExeptionClass("Could not do something. {}".format(e)) 这样的事情有什么区别?以他的方式提出异常有什么好处吗?
对 some_function() 的函数调用的输出是:
test = SampleClass()
test.some_function()
Traceback (most recent call last):
File "<input>", line 4, in some_function
File "<input>", line 10, in do_something
CustomException: Tried to do something and failed.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 6, in some_function
DifferentExceptionClass: ('Could not do something', CustomException('Tried to do something and failed.',))
编辑:无法联系到该同事发表评论。他们也很久以前写了这个库,可能不记得他们写这个时的“心情”。我认为如果其他人看到类似的实现,它也会对 SO 进行很好的讨论。
【问题讨论】:
-
不,您只需调用构造函数,它需要两个参数...
标签: python python-3.x exception-handling