LEVIATHAN v962456e · 962456eee1

Library

Exit codes — env::exit and env::setExitCode

How a program chooses its exit status, and what an uncaught exception does.

since 0.1.0-alpha.1linuxwindows

Description

A program that reaches the end without doing anything special exits with status 0. Two functions in the env namespace change that.

  • env::setExitCode(code) records the status the program will exit with, then lets execution continue. The program keeps running, the event loop drains (pending timers and sockets finish), and the recorded status is used when it finally exits. Calling it several times keeps the last value.
  • env::exit(code) ends the program now and does not return. Work still pending in the event loop is abandoned. The exit epilogue still runs first, so a terminal that was put into raw mode is restored, and output that was buffered is flushed.

Both reduce the code to its low eight bits (code & 0xFF), which is all an operating system passes on: env::setExitCode(300) exits with 44.

An exception that reaches the top of the program uncaught is not a crash. The program prints Uncaught followed by the exception's type and message and exits with status 1.

setExitCode continues, exit stops

console.writeln("working");
env::setExitCode(0);
console.writeln("still running after setExitCode");
env::exit(0);
console.writeln("never printed");
working
still running after setExitCode

Rules

  • The default status is 0.
  • setExitCode(code) is recorded; the last call before the program ends wins.
  • exit(code) terminates immediately and never returns; code after it does not run.
  • The status is code & 0xFF.
  • An uncaught exception ends the program with status 1 and the message Uncaught <Type>: <message>.
  • Neither function can be used in comptime code.

Examples

The exit status is not visible in the program's output, so the next program is shown without being run. After it finishes, echo $? prints 3:

env::setExitCode(3);
console.writeln("done");
not run — exit status is not visible in stdout

env::exit(4) called from inside a timer callback would stop the whole program at that point, including any timer still waiting, and exit with status 4.

Notes

Neither function reports failure to its caller. To make the status depend on a result, compute it first and call env::setExitCode once at the end.

See also

  • env — The running process: its command-line arguments, its environment variables, and how it exits.
  • Timer — A source of ticks on the event loop.