TExcelTAD
Home › WebAssembly › Traps & Error Handling

Traps & Error Handling

A trap is WebAssembly's reaction to something that must not continue: the current call is aborted immediately, all the way out to the host, and the host sees an exception (WebAssembly.RuntimeError in JavaScript). A trap can't be caught inside core WebAssembly, and it never corrupts memory: it happens before the bad operation takes effect.

What traps

Cause Example V8 message
unreachable instruction a "this can't happen" path unreachable
integer division/remainder by zero i32.div_s x 0 divide by zero / remainder by zero
signed overflow in division i32.div_s -2147483648 -1 divide result unrepresentable
out-of-bounds memory access i32.load past the end memory access out of bounds
float → int out of range i32.trunc_f64_s 1e20 float unrepresentable in integer range
bad indirect call null slot or wrong type null function or function signature mismatch
table index out of range call_indirect / table.get table index is out of bounds
call stack exhausted runaway recursion (V8 reports a RangeError)

Messages differ between engines (Firefox and Safari word them differently), but the conditions are specified exactly, so every engine traps in the same places.

unreachable

unreachable traps unconditionally. Compilers emit it after calls that never return, for impossible switch cases and for Rust's panic! in release builds (panic = "abort"):

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func $weekday_hours (param $day i32) (result i32)    ;; day 0..6
    (if (i32.gt_u (local.get $day) (i32.const 6))
      (then (unreachable)))                             ;; caller broke the contract
    (select (i32.const 0) (i32.const 8) (i32.ge_u (local.get $day) (i32.const 5))))
  (func (export "main")
    (call $log (call $weekday_hours (i32.const 2)))
    (call $log (call $weekday_hours (i32.const 6)))
    (call $log (call $weekday_hours (i32.const 9)))
    (call $log (i32.const 999))))
8
0
RuntimeError: unreachable

The output shows two results, then the trap. The last log never runs: a trap aborts the whole call stack.

The integer overflow corner case

INT_MIN / -1 would be +2147483648, which doesn't fit in an i32. Instead of wrapping like add does, signed division traps:

wat · try it yourself
(module
  (import "console" "log" (func $log (param i32)))
  (func (export "main")
    (call $log (i32.mul (i32.const -2147483648) (i32.const -1)))     ;; mul wraps: no trap
    (call $log (i32.rem_s (i32.const -2147483648) (i32.const -1)))   ;; rem is defined: 0
    (call $log (i32.div_s (i32.const -2147483648) (i32.const -1)))))  ;; traps
-2147483648
0
RuntimeError: divide result unrepresentable

Errors without traps: return codes

Traps are for bugs and fatal conditions. Expected errors (bad input, file not found) are normally reported with return values, as in C: an error code, a sentinel, or a (value, ok) pair with multi-value. Here's a "safe" division that refuses to trap:

wat · try it yourself
(module
  (import "console" "log" (func $log2 (param i32 i32)))
  ;; returns (result, error): error 0 = ok, 1 = division by zero, 2 = overflow
  (func $checked_div (param $a i32) (param $b i32) (result i32 i32)
    (if (i32.eqz (local.get $b))
      (then (return (i32.const 0) (i32.const 1))))
    (if (i32.and (i32.eq (local.get $a) (i32.const -2147483648))
                 (i32.eq (local.get $b) (i32.const -1)))
      (then (return (i32.const 0) (i32.const 2))))
    (i32.div_s (local.get $a) (local.get $b))
    (i32.const 0))
  (func (export "main")
    (call $log2 (call $checked_div (i32.const 42) (i32.const 6)))
    (call $log2 (call $checked_div (i32.const 42) (i32.const 0)))
    (call $log2 (call $checked_div (i32.const -2147483648) (i32.const -1)))))
7 0
0 1
0 2

Catching traps from JavaScript

The host can catch a trap: it arrives as a WebAssembly.RuntimeError. The instance stays usable afterwards, and its memory and globals keep whatever state they had when the trap happened. The module below exports divide(a, b), a plain i32.div_s:

js · try it yourself
const bytes = new Uint8Array([
  0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
  0x01, 0x07, 0x01, 0x60, 0x02, 0x7f, 0x7f, 0x01, 0x7f,                 // type: (i32, i32) -> i32
  0x03, 0x02, 0x01, 0x00,                                               // one function of type 0
  0x07, 0x0a, 0x01, 0x06, 0x64, 0x69, 0x76, 0x69, 0x64, 0x65, 0x00, 0x00, // export "divide"
  0x0a, 0x09, 0x01, 0x07, 0x00, 0x20, 0x00, 0x20, 0x01, 0x6d, 0x0b,     // local.get 0, local.get 1, i32.div_s
]);
const { instance } = await WebAssembly.instantiate(bytes);
const { divide } = instance.exports;

for (const [a, b] of [[84, 2], [1, 0], [-2147483648, -1], [7, -2]]) {
  try {
    console.log(`${a} / ${b} =`, divide(a, b));
  } catch (err) {
    console.log(`${a} / ${b} trapped:`, err instanceof WebAssembly.RuntimeError, err.message);
  }
}
84 / 2 = 42
1 / 0 trapped: true divide by zero
-2147483648 / -1 trapped: true divide result unrepresentable
7 / -2 = -3

Note: If a trap happens halfway through updating a data structure in linear memory, that structure may be left inconsistent. After a trap, many applications throw the instance away and create a fresh one.

Debugging traps

  • Browser DevTools stop on the trapping instruction and show the Wasm call stack in text format. Building with debug info (-g for clang/Emscripten, the default dev profile in Rust) adds DWARF info so you see source lines.
  • Rust's console_error_panic_hook and Emscripten's ASSERTIONS=1 turn bare unreachable traps into readable messages.
  • Most "memory access out of bounds" traps are use-after-free, a bad pointer, or reading a JS view after memory growth.

Test yourself

Can WebAssembly code catch a trap with core instructions?

  1. Yes, with br_if
  2. No, a trap unwinds out to the host
  3. Yes, with select
  4. Only for division by zero

Which of these does NOT trap?

  1. i32.div_u by zero
  2. i32.mul overflow
  3. i32.trunc_f64_s of NaN
  4. loading past the end of memory

What does JavaScript receive when an exported function traps?

  1. undefined
  2. A WebAssembly.RuntimeError exception
  3. The value -1
  4. A rejected Promise