Raise an exception from the caller's scope? [duplicate]

我只是一个虾纸丫 提交于 2019-12-06 13:41:11

tl;dr: probably yes, but I can't imagine that it's a good idea.

I'm going to assume that we could, if we tried hard enough, fake up a callstack to show an exception coming from a different place. But I don't think that's a good idea.

In the first place, it's generally understood that the function which raises an exception is not always at fault. If somebody broke the contract and passed you a parameter which you don't expect, it's okay to raise an exception. If this is intended to cover your ass by raising the exception in the caller's scope so nobody blames your function, I think that somebody (maybe you, maybe your automated testing's "blame" system) needs to re-think how they determine responsibility.

In the second place, I don't think you can define the "right" scope very well. You might imagine that it should always be raised in your caller's scope, because clearly it's not your fault. Well, what if it's not their fault either? Should every function just throw up their hands and say "wasn't my fault" when an exception occurs? Pretty soon our stacktraces will say nothing at all.

Even if you're right, and your function is blameless, you're about to make everybody else's life hell, because manipulating the callstack to hide your function will make everybody scratch their heads, and remove valuable evidence for debugging the situation.

This might seem like a good idea, but I don't think it is, and I think if you put yourself in someone else's shoes you could understand how difficult it would make their life to try to use a function that behaved this way.

JAB

I would suggest catching the exception at the point you want to be at the top of the call stack and then raise a new exception wrapping the old one (so that you can reference the original call stack to know what exception actually caused the problem; after all, what happens when print "Success!" fails because, say, somebody set sys.stdout = int?).


After some browsing, it seems that https://stackoverflow.com/a/2615442/138772 is exactly the kind of answer you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!