Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Error Handling

This chapter defines Forge’s error handling mechanisms. Forge uses a multi-layered approach: Result types for explicit error values, the ? operator for propagation, safe blocks for error suppression, must for crash-on-error semantics, and check for declarative validation.

Overview

Forge provides five complementary error handling mechanisms:

MechanismPurposeBehavior on Error
Result typeRepresent success/failure as valuesCarries error as data
? operatorPropagate errors up the call stackReturns Err from enclosing function
safe { }Suppress errors silentlyReturns null
must exprAssert success or crashRaises a runtime error
check exprDeclarative validationRaises a runtime error with description

These mechanisms serve different use cases:

  • Result + ? — For functions that can fail and callers that want to handle failures explicitly.
  • safe — For optional operations where failure is acceptable and the value can be null.
  • must — For operations that should never fail in correct code.
  • check — For input validation with readable error messages.

Runtime Errors

All Forge runtime errors are represented by RuntimeError, which contains a message string and an optional propagated value. When an error is not caught, it terminates the program with an error message.

Errors can be caught with try/catch:

try {
    let x = 1 / 0
} catch e {
    say e.message    // "division by zero"
    say e.type       // "ArithmeticError"
}

The catch variable receives an object with message and type fields. Error types are inferred from the error message content:

Error TypeTriggered By
TypeErrorMessage contains “type” or “Type”
ArithmeticErrorMessage contains “division by zero”
AssertionErrorMessage contains “assertion”
IndexErrorMessage contains “index” or “out of bounds”
ReferenceErrorMessage contains “not found” or “undefined”
RuntimeErrorAll other errors

Subsections

The following subsections define each error handling mechanism in detail: