简体   繁体   English

如果到达代码中的非法位置,将引发哪个异常?

[英]Which exception to raise if arrived at an illegal location in code?

My code needs to process either a file or a directory (either of them is accepted from the shell as arguments from argparse ). 我的代码需要处理文件或目录(从shell接受它们中的任何一个作为argparse参数)。

The relevant snippet is: 相关代码段是:

if in_dir:
    in_glob = os.path.join(in_dir, "*." + ext)
elif in_file:
    in_glob = in_file
else:
    # Should never arrive here!
    print("error: neither input file, nor input directory are set.")
    raise SystemExit

In the else stanza (which should never be entered), I'd like to raise a more informative exception than SystemExit - to indicate that the control-flow arrived at an illegal location. else节(永远不应输入)中,我想提出比SystemExit更具信息性的异常-表示控制流到达了非法位置。

Which exception would you recommend I raise? 您会建议我提出哪个例外?

Many other languages have an assert_not_reached function for this purpose, but python does not. 许多其他语言为此目的提供了assert_not_reached函数,而python没有。 It's commonly subsituted with 通常用

assert False, 'this should never be reached'

or something similar. 或类似的东西。

我建议使用SystemErrorEnvironmentError但也将方便使用IOErrorLookupError

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM