throw: Wasm exception handling instruction
The throw exception handling instruction throws an exception of a specified type, as defined by a tag definition.
Try it
(module
;; Import the error tag from JS
(tag $my_error (import "env" "my_error") (param i32))
(func $might_throw (param $value i32)
;; If value is negative, run the if block
(local.get $value)
(i32.const 0)
(i32.lt_s)
(if
(then
;; Push the error code onto the stack, then throw an exception
(i32.const 42) ;; error code payload
(throw $my_error) ;; throw with the tag
)
)
)
(export "might_throw" (func $might_throw))
)
// Define error tag in JS
const myErrorTag = new WebAssembly.Tag({ parameters: ["i32"] });
// Import the tag into the module
const env = {
my_error: myErrorTag,
};
WebAssembly.instantiateStreaming(fetch("{%wasm-url%}"), { env }).then(
(result) => {
try {
// Negative value causes function to throw
result.instance.exports.might_throw(-1);
} catch (e) {
if (e instanceof WebAssembly.Exception && e.is(myErrorTag)) {
// 0 is the first payload value, which is equal to 42
const errorCode = e.getArg(myErrorTag, 0);
console.log("Error code:", errorCode);
} else {
// Throw other errors
throw e;
}
}
},
);
Syntax
throw identifier
throw-
The
throwinstruction. identifier-
An identifier for the exception tag type to throw. This can be:
- An identifying name, as defined by the
identifierof the corresponding tag type. - A tag index number —
0to identify the first specified tag,1for the second, etc.
- An identifying name, as defined by the
Type
[payload1, payload2, payloadN] -> []
payloadvalues-
The payload values, which typically represents identifying error codes.
The payload values can be retrieved when the exception is caught, either by clauses such as catch and catch_ref, or in JavaScript via a try...catch statement.
See the tag definition reference page for examples of both.
Binary encoding
| Instruction | Binary format | Example text => binary |
|---|---|---|
throw |
0x08 x:tagidx |
(throw $tag (i32.const 42)) => 0x41 0x2a 0x08 0x00 |