[英]Which exception should I throw if a module is not the correct version?
This may have been asked before or I may be overly pedantic, but my own searches have come up empty. 可能之前有人问过这个问题,或者我可能太学究了,但是我自己的搜索空了。
Looking through the Python 2.x exceptions page , I'm not sure which one I should raise
if my script determines that the __version__
of a module that's been imported, eg cv2
, is not the correct version. 通过寻找的Python 2.x的异常页 ,我不知道我应该哪一个
raise
,如果我的脚本确定__version__
一个已经导入的模块,例如cv2
,是不正确的版本。 For example, a script I'm working on requires OpenCV version 3; 例如,我正在处理的脚本需要OpenCV版本3; what's the best exception to
raise
in the following block if it determines that the version != 3? 如果确定版本!= 3,则在以下块中
raise
的最佳例外是什么?
import cv2
if not cv2.__version__.startswith('3'):
raise ValueError('OpenCV _3_ required')
You can create you own custom exception if the existing ones don't suffice. 如果现有的异常不足,则可以创建自己的自定义异常。
class VersionError(Exception):
def __init__(self, msg):
Exception.__init__(self,msg)
You've got a lot of options depending on what you want to do with this exception... Generally, I'd expect the install scripts to handle setting up the appropriate versions of dependencies so I might think of this as a simple runtime assertion -- Therefore AssertionError
may be appropriate. 根据此异常的处理方式,您有很多选择...通常,我希望安装脚本能够处理相应版本的依赖项,因此我可能会将其视为简单的运行时断言-因此
AssertionError
可能是适当的。
This one is really nice -- You don't need an if
statement, just an assert
: 这真的很好-您不需要
if
语句,只需要一个assert
:
assert cv2.__version__.startswith('3'), 'OpenCV _3_ required'
My next bet would be to use RuntimeError
as that is really meant to be a general exception that happens at runtime (and isn't usually meant to be caught)... It's a pretty general "Oh snap, something bad happened that we cannot recover from. Lets just spit out an error to let the user know what happened". 我的下一个赌注是使用
RuntimeError
因为这实际上意味着它是在运行时发生的一般异常(通常并不意味着被捕获)……这是一个非常普遍的现象,“哦,糟糕,发生了一件很糟糕的事,我们无法让我们吐出一个错误,让用户知道发生了什么。”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.