Skip to content

Commit

Permalink
Document System.exit usage
Browse files Browse the repository at this point in the history
Resolves #1855

Signed-off-by: Tadaya Tsuyukubo <tadaya@ttddyy.net>
  • Loading branch information
ttddyy authored and remkop committed Dec 20, 2022
1 parent fc8aa03 commit 27fd59a
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions docs/index.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -3620,6 +3620,9 @@ fun main(args: Array<String>) {

CAUTION: Older versions of picocli had some limited exit code support where picocli would call `System.exit`, but this is now deprecated.

When an application is not appropriate to call `System.exit`, for example it runs on the caller's process, you can take a different action based on the returned `int`.
See <<Usage of `System.exit`>> section for the usecases.

=== Generating an Exit Code

`@Command`-annotated classes that implement `Callable` and `@Command`-<<command-methods,annotated methods>> can simply return an `int` or `Integer`, and this value will be returned from `CommandLine.execute`. For example:
Expand Down Expand Up @@ -11401,6 +11404,31 @@ Multi-line text blocks can be used in command and option descriptions, headers a

For more details, see https://www.infoq.com/articles/java-text-blocks/[this article] by Java Language Architect Brian Goetz.

=== Usage of `System.exit`

When an application runs as an independent process, `System.exit` returns an exit code to the caller.
On the other hand, when an application runs as part of the caller process, `System.exit` halts the caller process and ends up an abrupt finish.

In such scenario, you need to avoid `System.exit`.

For example, picocli based <<TAB Autocomplete,TAB AutoComplete application>> solves this problem by having link:autocomplete.html#_maven_example[a system property] to determine whether to call `System.exit`.

Another usecase is https://www.mojohaus.org/exec-maven-plugin/[`exec-maven-plugin`] with https://www.mojohaus.org/exec-maven-plugin/java-mojo.html[`exec:java` goal].
This goal invokes the target class on the same maven process.
The `System.exit` call finishes maven process bypassing the rest of the maven steps including its error handlings.

In picocli, any exceptions thrown during the `CommandLine.execute` method are captured, printed, and converted to an exit code.
You can check the exit code and perform an appropriate action, such as throwing an exception, instead of calling `System.exit`.
Then, the caller(maven process) could perform its exception handlings.

[source,java]
----
int exitCode = new CommandLine(new MyCommand()).execute(args);
if (exitCode != ExitCode.OK) {
throw new IllegalStateException("MyCommand failed");
}
----


== Dependency Injection

Expand Down

0 comments on commit 27fd59a

Please sign in to comment.