Error Handling

Error Handling

Sun uses exceptions for recoverable errors: functions declare throws, return ordinary success values, and handle failures with try/catch. Unlike Rust's Result and Zig's error unions, errors propagate through stack unwinding rather than return values. Unlike C++ exceptions, Sun requires bounded payloads stored in reserved thread-local and stack memory, avoiding heap allocation for exception storage, and makes propagation explicit in function signatures.

Minimal example

read_value() returns an integer when its source is ready and throws ReadError otherwise. main() catches that exception and returns an exit status of 1.

/** Reports a failed read. */
exception ReadError {}
 
/** Returns a value or throws when the source is unavailable. */
function read_value(ready: bool) i32 throws {
  if (not ready) {
    throw ReadError();
  }
  return 42;
}
 
/** Handles a failed read. */
function main() i32 {
  try {
    return read_value(false);
  } catch (error: ReadError) {
    return 1;
  }
}

catch { ... } catches any Sun exception. extends defines exception families; the first matching catch wins. Inside a catch, throw; or throw error; rethrows the original concrete exception.

Exception storage

Exception payloads fit in 128 bytes, including padding. They support numeric values, booleans, characters, plain enums, and fixed-size arrays of these types; references, pointers, owning objects, generics, and exception destructors are not allowed. Propagation uses reserved thread-local and stack records.

Exception values now retain bounded physical stack traces. Destructors reserve independent nested records in their own frames when they may initiate an exception; caller cleanup does not reserve a duplicate record. There is no TLS pool.

ThreadExceptionState
baseException: PropagationRecordDepth-sized base record reserved after the aligned header, once per thread.
throwTarget: PropagationRecord*Selects baseException or a destructor’s stack record for the next throw.
PropagationRecord
unwindNative unwind header; remains at a stable address during propagation.
valueException type, payload, and inline stack trace. Catch storage holds this value without an unwind header.
ExceptionValue
typeIdentifies the concrete exception; null denotes a consumed value.
payloadBounded user fields, separate from trace capacity.
traceInline trace captured on the first throw and preserved on rethrow.
StackTrace
framesInline address array whose length is the configured trace depth.
countNumber of valid stored addresses.
statusComplete, truncated, partial, unavailable, or disabled. Inspect one extra frame to detect truncation.

Embedded values occupy storage inside their parent. A catch receives the ExceptionValue, including its trace; the native unwind header stays in place. The compiler generates these storage types with an inline address array sized to the configured trace depth. The precompiled runtime accesses their fixed fields and frame offsets; changing the depth does not recompile the runtime. The default trace depth is 16, with one extra frame inspected to detect truncation. Rethrows preserve the original trace.

Uncaught main exceptions and detected non-throwing boundary violations print Unhandled exception: Type, followed by calls from outermost to innermost and the original throw statement. Tree connectors use two spaces per nesting level. Explicit reports use Exception: Type instead. Release builds record source paths relative to the directory containing the entrypoint. Imported Moon paths retain the originating library’s entrypoint base, including generic bodies. Terminal call names expose these locations on hover through sun-source:ENTRYPOINT/path:line:column link targets. ENTRYPOINT means the originating program or library’s entrypoint directory, not the runtime working directory; these targets describe a location rather than an installed file. Redirected output shows ENTRYPOINT/path:line:column directly. Builds with -g retain absolute source paths and link directly to those files; VS Code terminals use editor links. Complete traces have no status footer.

Capture stores only addresses. During reporting, the runtime resolves them using source indexes prepared by the compiler, including inlined calls. This works without -g, external debug files, or a standard-library import. Optimized tail calls may be absent, and unknown frames within the Sun call chain fall back to addresses. Reporting does not call IError.message().

The reporter shares a locked 32 KiB buffer between threads, truncates long names, and marks reports that exceed the buffer. Source indexes are separate program metadata. Lookup and formatting do not allocate. Capture failure is reported as unavailable or partial and does not replace the exception. Stack walking also depends on the platform unwinder: allocation-denial tests cover indexed native frames and prepared Sun JIT modules on supported Darwin and glibc hosts. Unindexed foreign frames and static musl builds still need additional work before claiming an unconditional allocation-free trace guarantee.

At the default depth on supported 64-bit layouts, an exception value occupies 288 bytes and a propagation record occupies 320 bytes. The payload still has 128 bytes of capacity. Catch storage and destructor records can reserve stack space even on paths that do not throw. Destructors proven unable to initiate an exception omit their nested record. Rebuild Moon libraries and native runtime archives when adopting this exception layout.

Printing the current stack

Call _report_stack_trace() from ordinary code to print the current call stack. No active exception, throws annotation, or standard-library import is required. The report uses the same tree layout, source links, and capture depth configured by --exception-trace-depth. Its heading is Stack trace, and it has no throw row. It does not change any retained exception or its original trace.

/** Reports the call chain at this point. */
function diagnose() void {
  _report_stack_trace();
}

Printing a caught trace

The compiler intrinsics _exception_trace_frames(error) and _exception_trace_status(error) read metadata from a direct active catch binding, including a family catch. An ordinary unthrown exception has no trace metadata. The frames are a borrowed const ref array<u64>; they cannot outlive the catch or remain live while the exception is consumed by rethrowing it.

With the standard library imported, an ordinary ExceptionTrace value holds that borrow and its status. Pass it to helpers using const ref:

catch (error: ReadError) {
  var trace = std.ExceptionTrace(
    _exception_trace_frames(error), _exception_trace_status(error));
  std.print_exception_trace(trace);
}

std.print_exception_trace writes the same source-resolved calls and capture status to standard error without allocating, throwing, or consuming the exception. It calls the native runtime through an ordinary borrowed-array C boundary. A nested catch does not change an explicit view of the outer exception. The test runner reports retained traces once when it catches a test failure.

Configuring trace depth

Use --exception-trace-depth=N, where N is an integer from 0 through 256. The default is 16. Zero disables stack walking and removes the address array from exception records; payload capacity remains 128 bytes at every depth.

A project can set "exception_trace_depth": 0 in sun-config.json. The nearest project setting wins; an explicit command-line value overrides it. The setting applies to JIT execution, native compilation, tests, and Moon builds. Build hashes include it, so changing depth rebuilds artifacts and source dependencies.

Every imported Moon library must use the same depth, including the standard library. Incompatible depths and old exception modules without depth metadata are rejected. Rebuild libraries with the chosen flag before importing them. Native links compile the embedded runtime for nondefault depths. Nondefault JIT execution also requires clang++ or c++ on PATH: it builds a matching local runtime before program execution and keeps it loaded until the JIT is destroyed. This preparation may allocate; the throw, capture, and reporting paths do not use it. Cross-compilation uses the selected target toolchain for the runtime.

DepthException valuePropagation record
0160 bytes192 bytes
16288 bytes320 bytes
2562,208 bytes2,240 bytes

Allocation-denial checks currently validate the implementation on the Darwin host; Linux and the complete platform matrix still require validation.

Nested exceptions and stack traces

An exception can trigger cleanup that throws another exception. Here, foo() owns bar and throws A. While A unwinds the stack, bar's destructor throws and catches B. Both exceptions are briefly alive: B must have separate storage so handling it does not overwrite A. Once cleanup finishes, A reaches main()'s catch.

The tables below follow each transfer between stack and thread-local storage. The runnable example is examples/30-error_handling/main.sun; it exits with status 1.

/** Demonstrates a handled exception during cleanup of another exception. */
 
/** Reports the original failure. */
exception A {
}
 
/** Reports a failure during cleanup. */
exception B {
}
 
/** Performs cleanup that handles its own failure. */
class Bar {
  /** Creates the resource. */
  init() {}
 
  /** Handles B before allowing the original unwind to continue. */
  deinit() {
    try {
      throw B();
    } catch (error: B) {
      // B is handled here.
    }
  }
}
 
/** Throws A while owning a resource that requires cleanup. */
function foo() void throws {
  var bar = Bar();
  throw A();
}
 
/** Handles A after foo's resource has been destroyed. */
function main() i32 {
  try {
    foo();
  } catch (error: A) {
    return 1;
  }
  return 0;
}

Each color identifies a function frame or thread-local storage. Callers appear above callees. Rows show logical storage, not byte sizes: an empty error row is reserved catch storage, and each exception includes its trace. Runtime names are illustrative internals, not user-facing Sun declarations.

Step 1: foo throws A

A enters the thread-local base record. foo() needs no separate trace storage.

Stack
main() frame
error: AReserved catch storage; empty.
foo() frame
bar: BarLocal resource owned by foo; destroyed during unwinding.
Thread-local storage
Thread exception state
baseException: PropagationRecordOwns A while it propagates, including while cleanup handles B.
throwTarget: PropagationRecord*Pointer to baseException

Step 2: unwinding enters Bar.deinit

The destructor selects its own stack record for nested throws, saving the previous target. A stays in thread-local storage.

Stack
main() frame
error: AReserved catch storage; empty.
foo() frame
bar: BarLocal resource owned by foo; destroyed during unwinding.
Bar.deinit() frame
previousTarget: PropagationRecord*Saved pointer to the TLS base record holding A.
nested: PropagationRecordReserved propagation storage; empty and selected for nested throws.
error: BReserved catch storage; empty.
Thread-local storage
Thread exception state
baseException: PropagationRecordOwns A while the destructor prepares to handle nested throws.
throwTarget: PropagationRecord*Points to nested in the Bar.deinit() frame.

Step 3: the destructor throws B

B enters the destructor's selected record. A and B retain independent traces.

Stack
main() frame
error: AReserved catch storage; empty.
foo() frame
bar: BarLocal resource owned by foo; destroyed during unwinding.
Bar.deinit() frame
previousTarget: PropagationRecord*Saved pointer to the TLS base record holding A.
nested: PropagationRecordOwns B during native propagation.
error: BReserved catch storage; empty.
Thread-local storage
Thread exception state
baseException: PropagationRecordOwns A while it propagates, including while cleanup handles B.
throwTarget: PropagationRecord*Points to nested in the Bar.deinit() frame.

Step 4: the destructor catches B

B moves into catch storage, freeing the nested record for reuse. If B escapes the destructor instead, Sun terminates.

Stack
main() frame
error: AReserved catch storage; empty.
foo() frame
bar: BarLocal resource owned by foo; destroyed during unwinding.
Bar.deinit() frame
previousTarget: PropagationRecord*Saved pointer to the TLS base record holding A.
nested: PropagationRecordReserved propagation storage; empty and selected for nested throws.
error: BCaught exception B.
Thread-local storage
Thread exception state
baseException: PropagationRecordOwns A while it propagates, including while cleanup handles B.
throwTarget: PropagationRecord*Points to nested in the Bar.deinit() frame.

Step 5: the destructor returns and A resumes

The destructor restores the previous throw target and its frame expires. A resumes unwinding with its original trace.

Stack
main() frame
error: AReserved catch storage; empty.
foo() frame
bar: BarDestroyed; its storage remains until foo exits.
Thread-local storage
Thread exception state
baseException: PropagationRecordOwns A while it propagates, including while cleanup handles B.
throwTarget: PropagationRecord*Points to baseException

Step 6: main catches A

A moves into main()'s catch storage, freeing the TLS base record. The catch returns 1.

Stack
main() frame
error: ACaught exception A.
Thread-local storage
Thread exception state
baseException: PropagationRecordReserved base storage; empty after transfer to main’s catch.
throwTarget: PropagationRecord*Points to baseException

Standard-library exceptions

Standard-library operations throw concrete exceptions such as IndexOutOfBoundsError and AllocationError. IError exposes code() and message(); it is an interface, not an exception family. Calling message() creates an owned String and can itself throw.

using std;
 
/** Handles an invalid index and explicitly chooses whether to copy its message. */
function report() void throws {
  var values = Vec<i32>(std.mem.global_allocator, 1);
  try {
    values.get(10);
  } catch (error: IndexOutOfBoundsError) {
    var message = error.message();
    std.io.eprintln(message);
  }
}

Error stores a numeric code and up to 96 bytes of inline diagnostic text. Option<T> still represents absence. Tests can throw by default; failed assertions throw exceptions. Unhandled exceptions from main() currently print a fixed diagnostic and exit with status 1 after cleanup; worker threads must handle exceptions before returning.