If I expect specific arguments for a command call, and its called wrongly by the user, should the program throw an exception?
In python I would like to write something like:
assert 'author' in args, 'error: author not given'
the programm has to end, because the command call was wrong, but its not really unexpected that the command is called wrongly. So should i use exceptions or not?
-
2Does this answer your question? Exception handling in Python - Am I doing this wrong (and why?)gnat– gnat2020年09月13日 19:30:40 +00:00Commented Sep 13, 2020 at 19:30
-
1I think the down-votes might be coming because people are unsure what you mean by "command." I assumed "a command executed from the command line" and answered accordingly.Greg Burghardt– Greg Burghardt2020年09月13日 23:46:32 +00:00Commented Sep 13, 2020 at 23:46
1 Answer 1
The program should not throw an exception to the end user. In fact, no exceptions should be made visible to the end user.
The mere fact you say calling a command incorrectly is expected should tell you an exception is not the right way to handle this situation. This is more a question of user interface design than software development. What would you as a user expect? How would you like to be treated? An exception makes me think a problem occurred — something that I, the end user, cannot fix.
But maybe all I did was mistype something. I can correct that. In this case show a user friendly error message. Worse case scenario show the general "help" text for the command or sub command.
But this still doesn't fully answer your question. Inside the code for the command you can certainly throw an exception. Upon executing a sub command you could throw an exception given invalid input. Your higher level procedure for the command (think main()
in most languages) you should trap exceptions and translate that to something user-friendly.
So to answer your question, yes you should throw an exception, but catch it and handle it gracefully enough for the user to recover and correct their error.