What exit code does a failed require or assert give?
← Error Handling and Exceptions · Ref: Q1435
A failed require always ends the program with exit status 1. The language raises a Panic: a catch cannot see it, the finally blocks and the application teardown still run, and stderr gets one line that names the condition and where it is: 'Exception in thread "main" Panic: Requirement failed: `notscores.empty()` at <file>:<line>:<column>: Exit Code: 1'.
The code is always 1, so a require is not a way to report an outcome. It says the program has a bug. To end with a status you choose, throw an Exception with an exit code and do not catch it (see Q1432). For an outcome the program expects, return an Integer from the program (see Q1431).
AND assert?
assert is only allowed in dev source files (E81015 anywhere else), so a production program never contains one. Under 'ek9 -t' a false assert fails that test. The test runner reports it, and the ek9 command exits 11 ('tests failed'). That 11 is the ek9 command's own code, not a status from your program (see Q1437). In a test, assertPanic(expression) checks that a require really fails.
GUARD INSTEAD OF FAILING
If an empty list is a normal case, it is not a require. Check it first and choose what happens:
if scores.empty() stdout.println("No scores yet")
See Q304 for require. See Q305 for require vs assert vs throw. See Q1434 for Panic.
Example
defines module qa.errorhandling.requireexitone defines function averageOf() -> scores as List of Integer <- rtn as Integer? require not scores.empty() total <- Integer() cat scores > total rtn: total / length scores defines program RequireExitDemo() stdout <- Stdout() stdout.println(`Average: ${averageOf([4, 6, 8])}`) noScores <- List() of Integer stdout.println("Averaging an empty list") averageOf(noScores)
Common mistakes
E81015 — assert is a test construct and is only allowed in dev source files. A precondition in production code is a require, which fails with exit status 1. See ek9 -h E81015 for details.
Incorrect:
assert not scores.empty()
Correct:
require not scores.empty()
Other ways to ask this
- Can I set the exit code of a failed require?
- What happens to the process when a require fails?
- Why did my program exit 1 with 'Requirement failed'?
- What exit code does a failed assert give?
Coming from another language?
Java: a failed assert throws AssertionError, but only when -ea is on, and the program exits 1. Go: panic exits 2. Rust: panic! exits 101. EK9: a failed require always runs, cannot be caught, and exits 1. assert lives only in dev sources and fails a test (ek9 -t exits 11).
Keywords: exit code, exit 1, require, assert, panic, precondition, Requirement failed, test failure