简体   繁体   中英

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 ).

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.

Which exception would you recommend I raise?

Many other languages have an assert_not_reached function for this purpose, but python does not. It's commonly subsituted with

assert False, 'this should never be reached'

or something similar.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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