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.