Click internally uses exceptions to signal various error conditions that the user of the application might have caused. Primarily this is things like incorrect usage.
Click’s main error handling is happening in BaseCommand.main(). In there it handles all subclasses of ClickException as well as the standard EOFError and KeyboardInterrupt exceptions. The latter are internally translated into a Abort.
The logic applied is the following:
Generally you always have the option to invoke the invoke() method yourself. For instance if you have a Command you can invoke it manually like this:
ctx = command.make_context('command-name', ['args', 'go', 'here'])
with ctx:
result = command.invoke(ctx)
In this case exceptions will not be handled at all and bubbled up as you would expect.
Starting with Click 3.0 you can also use the Command.main() method but disable the standalone mode which will do two things: disable exception handling and disable the implicit sys.exit() at the end.
So you can do something like this:
command.main(['command-name', 'args', 'go', 'here'],
standalone_mode=False)
Click has two exception bases: ClickException which is raised for all exceptions that Click wants to signal to the user and Abort which is used to instruct Click to abort the execution.
A ClickException has a show() method which can render an error message to stderr or the given file object. If you want to use the exception yourself for doing something check the API docs about what else they provide.
The following common subclasses exist: