Python 中 .Net InvalidOperationException 的模拟是什么?
Python
中 .Net InvalidOperationException
的模拟是什么?
What is the analog for .Net InvalidOperationException
in Python
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
没有直接的等价物。通常
ValueError
或TypeError
就足够了,如果这两者都不适合,也许是RuntimeError
或NotImplementedError
。There's no direct equivalent. Usually
ValueError
orTypeError
suffices, perhaps aRuntimeError
orNotImplementedError
if neither of those fit well.我可能会选择以下两个选项之一:
自定义异常,最好定义如下:
类InvalidOperationException(异常):
通过
Just using
Exception
我不相信有直接的类似物; Python 似乎有一个非常扁平的异常层次结构。
I'd probably go between one of two options:
A custom exception, best defined as follows:
class InvalidOperationException(Exception):
pass
Just using
Exception
I don't believe there's a direct analogue; Python seems to have a very flat exception hierarchy.
我部分同意 Chris R 的观点——定义你自己的异常:
通过这种方式定义你自己的异常,你会得到很多好处,包括构建一个层次结构来满足你的需求:
不过,我不同意抛出一个赤裸裸的“异常”。
I'll partially agree with Chris R -- define your own:
You get much benefit from defining your own exceptions this way, including building a hierarchy to fit your needs:
I don't agree with throwing a naked "Exception", though.
在我看来,您应该这样做,
而不是定义自己的异常。请参阅下面的示例,了解这种情况更好:
它应该运行而不会出现任何错误。在执行
m*v
时,它尝试从Matrix2D
调用__mul__
,但失败。当且仅当它返回NotImplemented
时,它才会尝试从右侧的对象调用__rmul__
。In my opinion, you should do
instead of defining your own exception. See the example below for a case where this would be preferable:
It should run without any error. When doing
m*v
, it tries to call__mul__
fromMatrix2D
, but fails. If, and only if, it returnsNotImplemented
, then it tries to call__rmul__
from the object on the right side.