exceptions.md
This file
Path
docs/exceptions.md
162 lines · 5.6 KiB · Markdown
Last changed by
Stable (#3851)Rowlando13before adoption6aabf09
History of this fileTake it
Move Exceptions and Entry-points docs from reST to MyST (#3142)Rowlando13before adoption7f7bbe4
lines 1–21why, one step back1(exception-handling-exit-codes)=23# Exception Handling and Exit Codes45```{eval-rst}6.. currentmodule:: click7```89Click internally uses exceptions to signal various error conditions that10the user of the application might have caused. Primarily this is things11like incorrect usage.1213```{contents}14:depth: 115:local:16```1718## Where are Errors Handled?1920Click's main error handling is happening in {meth}`Command.main`. In21there it handles all subclasses of {exc}`ClickException` as well as theStable (#3851)Rowlando13before adoption6aabf09
line 22why, one step back22standard {exc}`EOFError` and {exc}`KeyboardInterrupt` exceptions.Move Exceptions and Entry-points docs from reST to MyST (#3142)Rowlando13before adoption7f7bbe4
line 23why, one step back23Stable (#3851)Rowlando13before adoption6aabf09
lines 24–27why, one step back24The table below lists every way a command can end, and what Click does25for each. The middle column is the default. The last column applies when26{meth}`Command.main` runs with ``standalone_mode=False``, which the next27section describes.Move Exceptions and Entry-points docs from reST to MyST (#3142)Rowlando13before adoption7f7bbe4
line 28why, one step back28Stable (#3851)Rowlando13before adoption6aabf09
lines 29–38why, one step back29| How the command ends | Standalone mode | ``standalone_mode=False`` |30| --- | --- | --- |31| It returns | Exit with code ``0`` | Return the value of {meth}`Command.invoke` |32| It called {meth}`Context.exit` | Exit with the given code | Return the given code |33| It raised a {exc}`ClickException` | Call {meth}`ClickException.show`, then exit with {attr}`ClickException.exit_code` | Propagate it |34| The user pressed {kbd}`Ctrl+C`, which raises a {exc}`KeyboardInterrupt` | Print a blank line, then ``Aborted!`` to standard error, and exit with code ``1`` | Print a blank line, then raise {exc}`Abort` with the original exception as its ``__cause__`` |35| The user pressed {kbd}`Ctrl+D`, or {kbd}`Ctrl+Z` on Windows, which raises an {exc}`EOFError` | The same as {kbd}`Ctrl+C` | The same as {kbd}`Ctrl+C` |36| It raised an {exc}`Abort` | Print ``Aborted!`` to standard error, and exit with code ``1`` | Propagate it |37| The output pipe closed early, which raises an {exc}`OSError` with ``EPIPE`` | Silence the flush errors, and exit with code ``1`` | The same |38| It raised any other exception | Propagate it | Propagate it |Move Exceptions and Entry-points docs from reST to MyST (#3142)Rowlando13before adoption7f7bbe4
line 39why, one step back39Stable (#3851)Rowlando13before adoption6aabf09
lines 40–43why, one step back40Click writes the message and exits once that handling is done. An41interrupt arriving during this last step cannot change the exit code the42table gave. It can only cost the message.43Move Exceptions and Entry-points docs from reST to MyST (#3142)Rowlando13before adoption7f7bbe4
lines 44–69why, one step back44## What if I Don't Want That?4546Generally you always have the option to invoke the {meth}`Command.invoke`47method yourself. For instance if you have a {class}`Command` you can48invoke it manually like this:4950```python51ctx = command.make_context("command-name", ["args", "go", "here"])52with ctx:53 result = command.invoke(ctx)54```5556In this case exceptions will not be handled at all and bubbled up as you57would expect.5859Starting with Click 3.0 you can also use the {meth}`Command.main` method60but disable the standalone mode which will do two things: disable61exception handling and disable the implicit {func}`sys.exit` at the end.6263So you can do something like this:6465```python66command.main(67 ["command-name", "args", "go", "here"],68 standalone_mode=False,69)Stable (#3851)Rowlando13before adoption6aabf09
lines 70–87why, one step back70```7172This is also how you replace the ``Aborted!`` message. Standalone mode73turns off every row of the table above, so catch the cases you want to74keep and write your own message for the rest:7576```python77try:78 command.main(79 ["command-name", "args", "go", "here"],80 standalone_mode=False,81 )82except click.Abort:83 click.echo("Bye!", err=True)84 raise SystemExit(1)85except click.ClickException as e:86 e.show()87 raise SystemExit(e.exit_code)Move Exceptions and Entry-points docs from reST to MyST (#3142)Rowlando13before adoption7f7bbe4
lines 88–162why, one step back88```8990## Which Exceptions Exist?9192Click has two exception bases: {exc}`ClickException` which is raised for93all exceptions that Click wants to signal to the user and {exc}`Abort`94which is used to instruct Click to abort the execution.9596A {exc}`ClickException` has a {meth}`ClickException.show` method which97can render an error message to stderr or the given file object. If you98want to use the exception yourself for doing something check the API docs99about what else they provide.100101The following common subclasses exist:102103- {exc}`UsageError` to inform the user that something went wrong.104- {exc}`BadParameter` to inform the user that something went wrong with105 a specific parameter. These are often handled internally in Click and106 augmented with extra information if possible. For instance if those107 are raised from a callback Click will automatically augment it with108 the parameter name if possible.109- {exc}`FileError` this is an error that is raised by the110 {class}`FileType` if Click encounters issues opening the file.111112(help-page-exit-codes)=113114## Help Pages and Exit Codes115116Triggering the a help page intentionally (by passing in ``--help``)117returns exit code 0. If a help page is displayed due to incorrect user118input, the program returns exit code 2. See {ref}`exit-codes` for more119general information.120121For clarity, here is an example.122123```{eval-rst}124.. click:example::125126 @click.group('printer_group')127 def printer_group():128 pass129130 @printer_group.command('printer')131 @click.option('--this')132 def printer(this):133 if this:134 click.echo(this)135136.. click:run::137 invoke(printer_group, args=['--help'])138139The above invocation returns exit code 0.140141.. click:run::142 invoke(printer_group, args=[])143```144145The above invocation returns exit code 2 since the user invoked the command incorrectly. However, since this is such a common error when first using a command, Click invokes the help page for the user. To see that `printer-group` is an invalid invocation, turn `no_args_is_help` off.146147```{eval-rst}148.. click:example::149150 @click.group('printer_group', no_args_is_help=False)151 def printer_group():152 pass153154 @printer_group.command('printer')155 @click.option('--this')156 def printer(this):157 if this:158 click.echo(this)159160.. click:run::161 invoke(printer_group, args=[])162```