Errors, options and assertions

Moth separates ordinary absence, recoverable failure and broken invariants. Use options for absence, implicit built-in failure for checked numeric work, typed Error! returns for explicit failure and assert only when continuing would violate an invariant.

catch protects a selected expression and accepts eligible safety catches even when authored arithmetic, a cast or multiple calls cannot fail. Eligibility does not create a failure effect. Assertions, resource exhaustion and fatal foreign-value integrity guards stay outside catch. A foreign integrity failure returned through a declared builtin Error! slot remains a typed Error and can be caught under ordinary compatibility rules. The Progress matrix owns current support: Progress.

Choose the explanation level: Error values

Error values

An Error carries a message and an unsigned numeric code.

missing = Error("Missing value")
coded = Error("Missing value", 200)

The code defaults to 0 and accepts 0 through 4294967295. A negative code is rejected, and an I32 variable needs an explicit fallible conversion.

Use the message to explain the failure. Use the code when a stable category is useful to callers or tools.

Code 0 does not mean success when a function returns the value as an error. Under the accepted contract, a bound catch for implicit numeric failure also receives Error. Typed errors keep their original message and code when caught.

The Progress matrix owns current backend support: Progress.

Error carries Moth's builtin structured error type.

Its public fields:

  • message String
  • code U32 = 0
missing = Error("Missing value")
coded = Error(message = "Missing value", code = 200)
large = Error("Quota exceeded", code = 3_000_000_000)

Contract for error values

  • message carries the human-readable explanation.
  • code carries a stable unsigned code and defaults to 0.
  • Codes above the signed 32-bit maximum are ordinary valid values, up to the maximum of U32.
  • A negative code or a code above the maximum of U32 fails at the ordinary typed boundary. A negative literal is a compile-time diagnostic, and an I32 variable needs an explicit fallible conversion.
  • code is a runtime error code, not a compiler diagnostic code.
  • Positional construction follows field order.
  • Named construction follows normal constructor argument rules.
  • Error is reserved by the language.
  • ErrorKind, ErrorLocation and StackFrame remain ordinary user-available names.

The Progress matrix owns current compiler and backend support: Progress.

Error! in a function signature marks an error return channel. It does not create a panic path and it is not a separate ordinary value type.

Custom structs and other compatible types may also be used as explicit error slot types. Under the accepted implicit-failure contract, built-in Error! materialises escaping checked failure. A custom E! slot requires local recovery or explicit mapping instead.

A bound catch for implicit failure receives Error. When implicit failure and built-in Error! share a catch, an existing typed error keeps its message, code and identity rather than being replaced by a generic numeric failure. Returning Error with code 0 is still an error, not success. An unbound catch need not construct an observable Error for implicit failure.

Transparent aliases preserve Error's built-in identity. A wrapper or an unrelated custom type does not gain automatic conversion. See Catch and recovery for compatibility rules and Progress for current compiler support.

Casts between String and Error are documented by Casts.

Choose the explanation level: Error returns

Error returns

A function with an explicit typed error path adds one final return marked with !.

parse_number |text String| -> I32, Error!:
    if text is "":
        return! Error("Missing number")
    ;

    return 42
;

Normal return sends success values.

return! sends one error value.

The caller must handle that error by propagating it or catching it.

Checked numeric work has a separate implicit built-in failure path. Under the accepted contract, Error! materialises that failure for callers. A custom error slot needs local recovery or explicit mapping with catch and return!.

Private functions without an error slot may propagate implicit failure inside their module. Exported callables must declare Error! or handle that failure locally. See Progress for current compiler support.

A function with an explicit typed error path marks one return slot with !.

parse_number |text String| -> I32, Error!:
    if text is "":
        return! Error("Missing number", 200)
    ;

    return 42
;

Signature contract

  • A function may declare at most one error-channel slot.
  • The error slot must be the final return slot.
  • Success slots appear before it.
  • A function may have success slots plus one error slot.
  • A function may also expose only an error slot.
  • Success return slots contain types only. The error slot may carry a channel.

The error slot type is explicit. Error! is common, but a compatible custom error type can be used when the function contract requires it.

Returning an error

return! expression leaves through the current function's error channel.

  • The current function must declare an error slot.
  • Exactly one error value is required.
  • The value must be compatible with the declared error type.
  • return! is terminal for the current path.
  • Normal success values use return.

Error-only functions

A function may declare only an error slot:

validate |ready Bool| -> Error!:
    if not ready:
        return! Error("not ready")
    ;
;
  • The arrow is required: -> Error!.
  • No success return value is required.
  • Normal fallthrough is valid when no error is returned.
  • A nested block may use return! too. The statement leaves through the enclosing error-only function's error channel and terminates that path.
Failure = |
    message String,
|

fail |message String| -> Failure!:
    return! Failure(message)
;

Implicit failure at function boundaries

Checked numeric work produces implicit built-in failure. It neither wraps nor implicitly panics. The enclosing handler or function contract delivers that failure under the accepted rules:

  • A private function with no error slot infers and propagates it within the same module.
  • A built-in Error! slot materialises the corresponding Error when failure escapes local handling.
  • A custom E! slot requires local recovery or explicit mapping to E, even in a private function.
  • An exported callable with no error slot must discharge implicit failure. Any remaining possibility is a compiler diagnostic.

These rules apply to zero, one and multiple success returns. The public rule also covers receiver methods, generics and re-exports. A transparent alias of Error keeps its built-in identity; an unrelated wrapper does not. User-defined failure-conversion traits, error-conversion hooks and generic adapter searches are outside Moth's design scope, so mapping into a custom error stays explicit. Current compiler support remains documented by Progress.

Map implicit failure into a custom error with catch and return!:

GeometryError ::
    InvalidDimensions,
;

area |width I32, height I32| -> I32, GeometryError!:
    result = width * height catch:
        return! GeometryError::InvalidDimensions
    ;
    return result
;

Returning a custom error on one path does not discharge another escaping implicit failure. Failure in a handler contributes to the surrounding function's contract. Statically known invalid numeric work remains a compile-time diagnostic, including inside Error! functions.

First-class public Result values and result pattern matching are outside the language's error-channel path. Explicit typed errors require propagation with ! or recovery with catch. Implicit private propagation is documented by Error propagation.

Choose the explanation level: Error propagation

Error propagation

Add ! after a call with a typed error return when the current function should pass that error to its caller.

wrapper |text String| -> I32, Error!:
    value = parse_number(text)!
    return value
;

On success, value receives the parsed number.

On failure, wrapper returns the error immediately.

The surrounding function needs a compatible error return slot.

Implicit numeric failure follows a different accepted rule. A private function without an error slot propagates it to callers within the same module without postfix !. An Error! function turns escaping implicit failure into Error; an exported function without an error slot must recover locally. See Progress for current compiler support.

Postfix ! propagates a typed error through the enclosing function's compatible error slot.

wrapper |text String| -> I32, Error!:
    value = parse_number(text)!
    return value
;

Contract for error propagation

  • The handled expression must have a fallible error channel.
  • The enclosing function must declare an error slot.
  • The produced error type must be compatible with that slot.
  • On success, the expression yields its success values.
  • On failure, the current function returns the error immediately.
  • A no-success fallible operation may still use postfix ! as a statement.
  • Multi-success fallible calls may feed a matching multi-bind.
items ~{4 I32} = {}

~items.push(value)!

Postfix propagation is not panic syntax.

Explicit casts use plain cast. A fallible conversion follows ordinary implicit or typed error delivery, with local catch or a compatible function boundary. See Casts for its target and evidence rules.

Removed forms

Old inline fallback and bang-handler spellings are invalid.

-- INVALID: old inline fallback and bang-handler spellings
value = parse_number(text)!0
value = parse_number(text) err!

Use catch then ... or a block catch: handler for recovery.

Implicit private propagation

Checked numeric failure is compiler-owned control flow, not a first-class source-visible Error! expression. Under the accepted contract, private functions without an error slot infer and propagate it within the same semantic module. Their internal callers do not add postfix !.

product |left I32, right I32| -> I32:
    return left * right
;

$export
checked_product |left I32, right I32| -> I32, Error!:
    return product(left, right)
;

$export
product_or_zero |left I32, right I32| -> I32:
    return product(left, right) catch then 0
;

checked_product materialises escaping implicit failure as a built-in Error. product_or_zero discharges it locally. An otherwise identical exported product without an error slot or recovery is rejected when multiplication may fail. Calling it with small values in one consumer does not repair its public contract.

A custom E! function must recover locally or map implicit failure explicitly with catch and return!. It receives no automatic conversion or hidden extra channel. Explicit typed errors still require ! or an applicable catch. See Error returns for the boundary rules and Progress for current compiler support.

Choose the explanation level: Catch and recovery

Catch and recovery

Use catch when a local fallback makes sense:

count = parse_number(text) catch then 0

The handler covers the complete selected expression, including arithmetic, receivers, call arguments, nested calls and cast operands:

total = left * right + offset catch then 0
amount = load_amount(left * right) catch then 0

Authored arithmetic or a valid cast can qualify for a safety catch even when the operation cannot fail. Two calls in the same expression also qualify:

chained = source.first().second() catch then fallback
pair = left() is right() catch then false

Calls inside an argument do not add to the enclosing call count:

-- INVALID safety catch when both calls are infallible
value = outer(inner()) catch then fallback

The nested call remains protected. If it can fail, its actual error makes the catch eligible. A safety catch does not claim a failure effect or catch fatal conditions.

The first failure skips later protected work. Earlier mutations and IO remain visible: a safety catch is not a transaction. Failure in the handler goes outwards rather than re-entering the same catch.

Implicit failure and compatible builtin Error! may share a handler. A bound error has type Error; existing typed errors keep their message, code and identity. A custom error cannot mix with implicit failure. Catch does not legalise statically invalid numeric work.

See Catch and recovery for handler constraints and placement.

catch handles the complete selected expression locally. It accepts compatible typed errors and recoverable implicit built-in failure. An eligible authored expression may also use a safety catch when no failure currently exists.

Protected expression

catch has lower precedence than ordinary operators. Parentheses around the protected expression are optional:

value = left * right + offset catch:
    then 0
;

The handler covers both arithmetic operations, receiver evaluation, arguments, nested calls and cast operands:

amount = load_amount(left * right + offset) catch then 0

If load_amount returns T, Error!, the handler covers that returned error and the arithmetic in its argument. Compatible typed calls inside the protected expression supply their success values without per-call postfix !.

Evaluate protected work once in ordinary source order. The first failure skips the remaining work and enters the handler, which replaces the expression's success values. Earlier mutations and IO remain visible. A catch is not a transaction, and failure in its handler goes outwards rather than re-entering it.

Safety-catch eligibility

Catch placement and catch eligibility are separate from actual failure effects. At a legal catch position, an authored expression qualifies through at least one of these conditions:

  1. It contains a valid authored cast.
  2. It contains a valid authored arithmetic operation, including unary numeric negation.
  3. It contains more than one function or member call at the selected expression's call-count level.
  4. Its evaluation contains an actual compatible typed or inferred recoverable failure producer.

Comparisons and Boolean operators alone do not count as arithmetic.

A signed literal such as -1 remains one literal and does not count as authored unary arithmetic. -value counts as an authored unary operation when value has a valid signed-integer or binary-float type. Compiler-inserted conversions, numeric helpers and hidden calls do not create eligibility. A constructor follows its existing constructor rules rather than counting as a function call.

Count calls through receiver chains and in separate operands. Do not add calls inside an argument to the enclosing expression's call count. That exclusion does not remove argument evaluation from the protected expression or hide authored arithmetic there. Ordinary grouping remains transparent. A nested handler owns its expression and fallback rather than lending their work to an outer catch.

Assuming named calls below cannot fail:

Expression

Safety catch

source.first().second()

Eligible: two receiver-chain calls

left() is right()

Eligible: two calls in separate operands

outer(inner())

Ineligible by call count: one outer-level call

outer(inner()), with fallible inner

Eligible through the actual failure producer

left is right

Ineligible unless evaluation contains another qualifying operation

-value for a valid signed numeric type

Eligible: authored arithmetic

A supported infallible cast

Eligible: authored cast

A literal or one infallible call

Ineligible without another qualifying operation

Eligibility belongs to this source occurrence. A reference to a binding or constant does not inherit arithmetic or call counts from its initializer. Folding, constant substitution, inlining or optional check removal cannot erase authored eligibility. A proven-infallible operation does not create an error effect, and safety catches do not receive a new default warning.

Handler constraints and error types

The handler participates in ordinary receiving and numeric constraints even when failure analysis later proves it unreachable:

fallback U64 = 0
result = 1 + 2 catch then fallback

The fallback types the unresolved literal arithmetic as U64 before operator selection. A completed concrete result cannot change type to satisfy a fallback of another type. Catch cannot infer named arithmetic operands backwards.

When no error producer exists, a bound handler name has builtin Error type. When compatible typed producers exist, their error type determines the binding. Syntax-only eligibility never fabricates an Error producer or changes a custom error type.

Optional optimisation cannot change the handler binding type supplied by a declared producer, even when it removes that producer's failure check.

  • Implicit built-in failure can share a handler with builtin Error!.
  • A bound implicit error has type Error. Typed Error keeps its message, code and identity, including code 0.
  • One custom error type can share a handler only when no implicit failure remains.
  • A custom E! mixed with implicit failure is rejected.
  • Two distinct typed error types are rejected, including custom E with builtin Error.

An unbound catch need not construct an observable Error for implicit failure. A bound catch materialises the compatible error.

Handler forms and result requirements

Use catch: for a block handler without an error binding, or catch |err|: when the handler needs the error:

value = parse_number(text) catch:
    then 0
;

other = parse_number(text) catch |err|:
    io.line(err.message)
    then 0
;

An inline handler closes on the line containing its opening :. A multiline handler closes with ; alone after its body. Handler placement follows Blocks and statements.

Inline recovery uses then on one logical line and has no statement body:

value = parse_number(text) catch then 0
other = parse_number(text) catch |err| then 0

When a receiving site needs success values, every reachable handler path must produce the required number and types with then, leave the function with return or return!, diverge through a standalone Never call or a proven terminal assertion, or leave through break or continue targeting a loop outside the handler. A break or continue consumed by a loop inside the handler does not complete it. The handler path must still produce, exit or diverge after that loop, and it cannot fall through without producing or exiting. Multi-success handlers match the expression's arity:

name, score = load_user(id) catch |err|:
    io.line(err.message)
    then "guest", 0.0
;

A fallible operation with no success values does not need then. The error binding is immutable, visible only in the handler and cannot shadow another visible name. Its type follows the compatible producers described above.

Validate these rules even for a handler later erased as unreachable.

Every handler gets ordinary validation even if it cannot run. Validate names, types, access, casts, generic evidence, required constant expressions and all-path value or terminality rules. A handler cannot hide an unsupported cast, incompatible fallback or statically invalid numeric operation.

Unreachable handler erasure

Wait until semantic typing and the applicable failure-summary convergence prove that recovery cannot execute. Then remove the handler's executable contribution through the existing construction/finalisation owner. Emit no handler work, runtime captures, inactive generic requests, reachable backend requirements or executable link facts. Preserve source graph membership and ordinary declaration and visibility validation.

Do not prune a handler because a provisional failure summary appears empty. Revalidate rewritten HIR and recompute affected borrow, proof and link facts before publication. Later optional lowerer optimisation may remove checks or blocks without changing source acceptance.

Existing recovery boundaries

  • catch and postfix ! or optional ? conflict on the same expression. Postfix ! remains ordinary function-call propagation.
  • Explicit propagation exits the function and does not target the nearest catch.
  • Catch bodies remain statement-like and stay out of conditions, templates and constants, except for directly foldable cast recovery at an explicit constant/default receiver.
  • Commas, parentheses, logical-line boundaries and statements delimit the selected expression.
  • Fallibility is a separate result channel, not a first-class value that can be stored.
  • Assertions, resource exhaustion, fatal foreign-value integrity guards and host termination remain outside catch.

A catch on an assignment's right-hand expression protects that expression only. Compound arithmetic and checked conversion back remain separate checks, and the target changes only after success. To recover a complete update locally, catch a private helper call or compute and check the replacement before assignment. Catch cannot follow a loop or provide one grouped handler for several statements.

then and closed receiving sites are specified by Value-producing if.

Choose the explanation level: Options

Options

Use T? when a value may be missing and that absence is normal.

nickname String? = none

A normal String can be used where String? is expected.

Inspect a present value with is |name|:

display_name = if nickname is |name| then name else "guest"

Use postfix ? inside a function that also returns an optional value:

get_display_name |id String| -> String?:
    user = find_user(id)?
    return user.name
;

If find_user returns none, the current function returns none too.

T? is an optional value that may contain T or may be absent.

none is the only special absent value.

name String? = none
fallback String? = "guest"

Contextual wrapping

A value of T can be used where T? is expected.

none requires an immediate optional receiving context. It is not a standalone inferred type.

Optional values are not automatically unwrapped.

Present-value inspection

Inline inspection:

display_name = if maybe_name is |name| then name else "guest"

Block inspection:

display_name = if maybe_name is |name|:
    then name
else
    then "guest"
;

Statement inspection:

if maybe_name is none:
    io.line("missing")
;

Full option match:

label = if maybe_name is:
    "Priya" => then "Hi Priya"
    |name| => then name
    none => then "guest"
;

Option patterns support:

  • none
  • compatible literal present-value patterns
  • compatible relational present-value patterns
  • |name| to capture any present value
  • guards
  • else =>

An option match can be exhaustive without else => when it has both an unguarded none arm and an unguarded present-value capture.

Direct fallback syntax such as maybe_name else then "guest" is invalid.

Absence inspection

Statement if can test for absence:

if maybe_name is none:
    io.line("missing")
;

Equality and ordering

Options support equality comparisons:

present = maybe_name is "Priya"
absent = maybe_name is none
same = a is b

Two options can be compared only when they have the same option type and their inner type supports equality. Two absent values compare equal. Present values compare through the inner type's equality rule, and a present value never equals none.

Ordering operators such as < on optional values are not supported.

Postfix propagation

Postfix ? unwraps a present value or returns none from the enclosing function.

get_display_name |id String| -> String?:
    user = find_user(id)?
    return user.name
;

The exact contract is:

  • the operand must be optional
  • the enclosing function must have exactly one success return slot
  • that success slot must be a compatible optional type
  • the present payload becomes the expression result
  • absence returns none immediately
  • ? cannot be followed by catch

Options are compiler-owned value shapes. Source code does not construct public Option variants.

MON data boundary

Source optional rules above are unchanged. MON literal data documents the same explicit none by reference: optionality permits none, but only an explicit field default permits omission, so a missing optional field without a default is an error. Missing fields, explicit none and empty values stay distinct; defaults are prevalidated data applied only at the exact missing field, a supplied none is never replaced, and nested records are never deep-merged. That contract is Rust-only serialised-data documentation. See MON format.

Choose the explanation level: Assertions

Assertions

Use assert for a condition that must already be true.

assert(index < items.length())
assert(index < items.length(), "index must be in bounds")

The message is optional. When you add one it is an ordinary String? value, including a local string, runtime template snapshot or infallible string-producing call. It is still fully checked and normalized when the condition is the literal true. The message is normalized through the ordinary AST template path before it is discarded after final AST type/TIR validation, so its temporary AST-local TIR is removed with the message and no TIR reference, runtime handoff, generated function or other runtime fact survives. Active messages are evaluated only on the failure edge. The Progress matrix owns current compiler and backend support: Progress.

Message construction must not escape through !, ?, return, break or continue, or through escaping implicit or typed failure. Handle fallible work before the assertion and pass an infallible message.

A false condition stops the current program path. Failure while computing the condition is not a false assertion result. It follows the enclosing failure contract instead.

Assertion failure is not a recoverable error and cannot be caught.

assert(false) ends the current path. That proves divergence for the path, but it is not a Never value and does not by itself declare -> !.

Assertions remain checked in development and release builds.

Use Error! for failures callers are expected to handle. Use assert for broken assumptions and impossible states.

assert provides an always-checked statement intrinsic for invariants.

The accepted end-state contract uses one required condition and one optional message:

assert |condition Bool, message String? = none|

This is compiler-owned metadata, not an importable or shadowable Moth function. These rules describe the accepted contract. The Progress matrix owns current compiler and backend support: Progress.

assert(index < items.length())
assert(index < items.length(), "index must be in bounds")
assert(false, "unimplemented backend path")

Accepted forms

assert(ready)
assert(ready, "must be ready")
assert(condition = ready)
assert(ready, message = "must be ready")
assert(message = "must be ready", condition = ready)
assert(condition = ready, message = none)
  • The condition must resolve to Bool.
  • The condition is required.
  • The message resolves to String? and defaults to none.
  • A String promotes to String? through ordinary contextual coercion.
  • none selects the default failure text, "assertion failed".
  • A present message may be an ordinary infallible expression, including a local string, runtime template or infallible string-producing call.
  • Moth does not implicitly stringify other value types for an assertion message.
  • Named and positional arguments use the ordinary call rules. Positional arguments must come first, names must be condition or message, and a parameter cannot be supplied twice.
  • Mutable access markers are invalid for both parameters.
  • Parentheses are required.
  • The shared call-argument grammar owns trailing-comma behaviour.

The message is type checked, generic-inferred, evidence-checked and fully normalised, including nested templates, even when the condition is compile-time true. The inactive message is then replaced with typed none before the AST/HIR boundary. Its private generic calls still undergo concrete failure validation, but validation-only sidecars are removed before executable publication. No inactive TIR, runtime handoff or executable message demand survives. An active message is evaluated only on the failure edge. A template-backed message is read as one snapshot at failure and does not create an assertion sink or live subscription. Message construction cannot escape its evaluation through !, ?, return, break or continue, or through escaping implicit or typed failure. This includes inferred failure from a private call without an error slot. Handle fallible message work before the assertion and pass its infallible value instead.

Failure behaviour

  • Assertions are checked in development and release builds.
  • Failure is unrecoverable in Moth source.
  • Failure does not produce Error!.
  • Postfix ! is invalid.
  • catch is invalid.
  • Expected runtime failures should use an implicit failure or typed error path instead.

The condition is evaluated normally. Implicit failure or a typed error while computing it is not a false Bool result and does not trigger assertion failure or message evaluation. That failure follows the enclosing handler or function contract. A typed error still requires its ordinary explicit handling.

Statement-only contract

assert:

  • cannot be assigned
  • cannot be passed as an argument
  • cannot be imported or aliased
  • cannot appear in template interpolation
  • does not produce a value

assert(false) and assert(false, "message") are statically terminal. assert(false, runtime_message) is also statically terminal after the failure-edge message is lowered.

They may end a function path that otherwise requires a value.

A compile-time-false assertion proves that the current path diverges. It is not a Never value and does not create a -> ! contract. Only an explicit -> ! signature propagates divergence across a call. See Function declarations.

A dynamic assert(condition) is not statically terminal because the condition may succeed.

Choose the explanation level: Runtime failures and termination

Runtime failures and termination

Checked operations and typed errors support recovery. Resource exhaustion and host termination remain outside that contract. Choose Advanced for the failure catalogue and the Wasm/JavaScript comparison.

This reference records the accepted boundary between recoverable Moth failures and termination that prevents a handler from running. The Progress matrix owns current compiler and backend support: Progress.

Update the semantic catalogue when an operation, resource limit or failure contract changes.

Recoverable failure and termination

Moth separates a computation that cannot produce its normal result from an execution environment that can no longer support the program.

Checked numeric operations produce implicit built-in failure. Their enclosing handler or function contract delivers it, without wrapping or an implicit panic. Private functions with no error slot infer and propagate that failure within the same module, without postfix ! at each internal call. An explicit built-in Error! return channel materialises escaping failure as the corresponding Error. A custom error channel requires local recovery or explicit mapping. Exported callables expose their failures through a declared error channel or handle them before returning. The compiler diagnoses any implicit failure left unrepresented at that boundary.

Expression-wide catch handles the whole selected expression, including arithmetic, receivers, arguments and nested calls. Parentheses are not required. Implicit failures and built-in Error! outcomes may share one catch. The same rule applies to cast expression catch, so its handler may receive an arithmetic failure from the operand as well as a conversion error. A bound implicit-failure handler receives Error; an unbound handler need not construct an observable error value. Typed Error values keep their message, code and identity, including code 0.

One custom error type without implicit failure may share a catch. Custom errors mixed with implicit failure and two distinct typed error types are rejected. Split an expression or map its errors explicitly when its sources need different handling. Catch and recovery owns placement, boundary and explicit-propagation conflict rules.

The implicit entry uses the built-in Error! rule and its generated caller reports an unsuccessful entry invocation. HTML publishes that invocation's runtime fragments only after success. Static HTML stays after failure. Release uses a generic safe notice, not the application error message as HTML. Entry runtime and fragments owns top-level propagation and entry delivery. docs/build-system-design.md > Development entry-error reports owns development presentation, host status and the rule that a runtime report does not poison global build success.

Handling an error does not undo earlier mutations or IO. Compile-time-known invalid numeric operations remain source diagnostics, including inside Error! functions and expressions followed by catch.

assert is the only way to author a deliberate panic. A failed assertion is unrecoverable in Moth and remains checked in release builds. catch handles Moth failure channels, not arbitrary JavaScript exceptions or Wasm traps.

An assertion's condition evaluates normally. Failure while computing it is not a false assertion result. The lazily evaluated message must not contain escaping implicit or typed failure, including inferred failure in a private call. Assertions owns the full condition and message contract.

Closed implicit-failure cause catalogue

Implicit built-in failure uses one closed cause catalogue. A bound implicit-failure handler receives the matching built-in Error with its code and message.

Code

Cause

Meaning

300

DivideByZero

Division or remainder with a zero divisor.

301

IntOverflow

Integer arithmetic or negation outside the result domain.

302

InvalidExponent

Exponentiation with an unsupported exponent value.

303

FloatNonFinite

Binary floating-point arithmetic with a non-finite result.

306

InvalidLoopStep

A dynamic range or collection loop step is zero.

307

RangeStepNoProgress

Range where a floating-point candidate stops advancing after rounding.

304 (FloatBoundaryNonFinite) marks a non-finite external binary-float boundary and 305 (FloatFormatInvariant) marks a defensive formatting check. Neither is ordinary implicit failure; each follows its declared integrity contract.

306 applies to range and collection loops. Its message is `Loop step cannot be zero`. A dynamic zero step fails before the loop checks its bounds or emptiness, so an empty or wrong-direction loop still reports it.

The catalogue is closed. Extend it only with a documented code plus backend parity tests that keep JS and Wasm message and code behaviour consistent. There is no public Failure type, no mandatory stack trace, no new Error fields and no diagnostic ID used as an error code.

Termination outside assert

The following cases remain outside the recoverable failure system. An infallible source operation promises no recoverable error result, not unlimited memory, stack space or execution time.

Where it can happen

What can stop execution

Why it is not an ordinary failure

Growable collection push, map growth, runtime strings and templates, independent copies or allocating Dec operations

Allocation exhaustion or refusal by the runtime allocator

Recovery is not a language guarantee. Propagation, cleanup and reporting may themselves need resources. Growable push keeps its no-error-channel contract and traps on allocation exhaustion.

Backing-store growth and runtime storage bookkeeping

An allocation-size, address-space, representable-capacity or runtime limit is exceeded

These are physical storage limits, not permission to wrap an address or corrupt memory. They remain fatal unless the particular API explicitly defines a recoverable limit error.

Recursion, deep call chains and calls into host code

Stack or host call-depth exhaustion

The host may stop execution before enough stack remains for normal Moth error propagation or cleanup. There is no recoverable stack-budget effect.

Foreign bindings, generated code or runtime internals

An unexpected host exception, invalid generated memory access or broken runtime invariant

A fault is not a declared API outcome. The host or tooling may report it, but Moth does not turn arbitrary faults into Error values or promise safe continuation.

The process, browser tab or embedding host

External termination, an execution limit or a host failure

The program cannot require an environment that has stopped executing it to run a handler. Even a final diagnostic is not guaranteed.

A full fixed-capacity collection is different from allocation exhaustion. Fixed push returns Error! when it has no free slot. Invalid collection indices and missing map keys also retain their documented typed error paths. Expected IO errors follow the called API's declared contract. Resource failure does not silently replace these ordinary errors.

Fatal resource handling still requires runtime checks that protect memory and storage invariants. Excluding recoverable allocation errors does not authorise unchecked address arithmetic or treating a refused allocation as valid storage. No assertion, fatal runtime fault or external termination guarantees rollback or completion of cleanup.

A Wasm trap ends the current invocation. It need not end the embedding process. In a JavaScript host it can surface as a WebAssembly.RuntimeError. Conversely, out-of-memory behaviour may include host termination rather than a catchable exception. Tooling that reports an unexpected startup fault is observing that fault, not adding a Moth recovery channel or proving a compiler bug. See the error-condition mappings and resource limits in the Wasm JavaScript embedding specification.

Checked operations and bare backend behaviour

The table compares Moth's required result with selected bare backend operations without Moth's semantic checks. It is not an unchecked Moth mode or a catalogue of exact generated instructions. Helpers and representations may differ. A backend must preserve Moth semantics wherever it supports the feature.

Arithmetic checks the selected semantic result domain, not an operand's storage width. U8 + U8 stays U8, so 255 + 1 overflows rather than producing a U32. A later conversion back to a different target is a separate checked boundary. Fixed-integer / produces F64 after common-integer eligibility; // stays integer division.

JavaScript's Number below means its binary64 primitive, not Moth's arbitrary-precision Dec family. A bare JavaScript Number operation does not enforce an I32 or U32 range. Bare BigInt operations have no fixed-width overflow limit, but still depend on host resources.

Operation or invalid condition

Moth outcome

Bare Wasm behaviour

Bare JavaScript behaviour

Integer addition, subtraction, multiplication or negation exceeds the result domain

Built-in overflow failure

Integer add, subtract and multiply wrap modulo the carrier width. Negation via subtraction wraps too.

Number may exceed the Moth range or round. BigInt keeps the mathematical integer rather than fixed-width wrapping.

Integer // has a zero divisor or the signed result-domain minimum divided by -1

Built-in division or overflow failure

Integer division traps on zero. Signed division also traps on that overflow pair.

BigInt division throws RangeError on zero but has no signed-width overflow. Number division can produce infinity or NaN.

Integer % has a zero divisor

Built-in division failure. Signed minimum % -1 is valid and equals zero.

Integer remainder traps on zero. Signed minimum remainder -1 returns zero.

Number remainder produces NaN on zero. BigInt remainder throws RangeError.

Binary floating-point / has a zero divisor

Built-in division failure

Floating-point division produces infinity or NaN rather than trapping.

Number division produces infinity or NaN.

Binary floating-point arithmetic produces a non-finite result

Built-in invalid-result failure

Floating-point operations admit infinity and NaN.

Number operations admit infinity and NaN.

Integer exponent is invalid or exponentiation exceeds a bounded result domain

Built-in exponent or overflow failure

No scalar exponentiation instruction. A helper's unchecked integer multiplies can wrap.

Number exponentiation can produce fractional or non-finite results. BigInt rejects negative exponents with RangeError.

Integer narrowing cannot represent the value, including compound-assignment write-back

Plain cast follows ordinary failure delivery. Compound write-back produces implicit failure. The target changes only on success.

Integer wrapping conversions and narrow stores discard high bits rather than range-checking the value.

Ordinary assignment does not narrow. Integer coercions and integer typed-array stores can wrap to their selected widths.

Binary-float-to-integer conversion has an out-of-range truncated result

Plain cast follows ordinary failure delivery. Compound write-back produces implicit failure.

Trapping truncation traps on an invalid conversion. Saturating conversion clamps instead.

Math.trunc does not enforce the destination range. Subsequent fixed-width coercion can wrap.

Binary-float narrowing rounds to a non-finite value

Plain cast follows ordinary failure delivery. F16 operations check at F16 precision.

f32.demote_f64 can produce infinity. F16 needs its separate representation contract.

Math.fround can produce infinity when rounding to binary32.

Runtime numeric text parsing is invalid, or an exact Dec conversion loses required information

Plain cast follows ordinary failure delivery

No general text or decimal-scale conversion instruction. Language helpers define the checks.

Number accepts some spellings Moth rejects. parseInt and parseFloat can accept a prefix. Decimal-scale exactness needs helpers.

Dec-family division or remainder has a zero divisor

Built-in division failure. Arbitrary precision removes fixed-width overflow, not invalid operands.

No scalar arbitrary-precision decimal operation. Runtime helpers supply it.

No native Moth decimal-scale operation. A helper using BigInt division must handle its zero-divisor RangeError.

A runtime loop step is invalid

Built-in failure under the loop contract. Finishing at the last endpoint does not require an overflowing sentinel.

Branches and arithmetic have no Moth loop contract.

Loops and arithmetic have no Moth loop contract.

Invalid collection index, missing map key or full fixed collection

The operation's declared Error! result

Linear-memory bounds are not logical collection bounds. Collection helpers enforce the API contract.

Arrays and maps do not implement Moth's typed error contract. Collection helpers enforce it.

Finite floating-point rounding is permitted. Underflow to a finite subnormal or zero is not an overflow failure. Binary-float-to-integer conversion truncates before checking the integer range. Dec scale narrowing instead requires exactness. The numeric reference and cast reference own the complete operator, arithmetic and conversion rules.

The raw comparisons use the Wasm numeric semantics, Wasm instruction semantics, ECMAScript Number and BigInt semantics, ECMAScript numeric conversions, ECMAScript Math operations and ECMAScript numeric parsing. These specifications describe the backend primitives, not an alternative Moth language contract.

What checks and optimisations promise

A backend may remove a check when it proves that the failing case cannot occur. More expensive release analysis may remove more checks, but source acceptance, exported contracts and observable failure order stay the same. Programmer confidence is not an unchecked assumption available to the optimiser.

Handling a checked failure with assert(false, ...) makes termination explicit. It does not automatically remove the original check. Wasm integer addition wraps rather than traps, so panic-on-overflow still needs detection. Native-trap substitution for assertion handlers remains unsettled. Any accepted optimisation would need to preserve the full observable assertion contract, including required message work.

Grouped if: handlers, rewind or rollback, richer effects, explicit wrapping, other wrap-or-trap controls and native-trap assertion optimisation remain unsettled. This reference reserves no syntax or guarantee that they will be added. $checked is the separate borrow-proof budget, not a numeric mode. Recoverable resource exhaustion is outside Moth's design scope, not another pending failure effect.