WebAssembly.Exception constructor
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since May 2022.
The WebAssembly.Exception() constructor is used to create a new WebAssembly.Exception object instance.
Syntax
new Exception(tag, payload)
new Exception(tag, payload, options)
Parameters
tag-
A
WebAssembly.Taginstance defining the data types expected for each of the values in thepayload. payload-
An array of one or more data fields comprising the payload of the exception. The elements must match the data types of the corresponding elements in the
tag. If the number of data fields in the payload and their types don't match, aTypeErrorexception is thrown. optionsOptional-
An object with the following optional fields:
traceStackOptional-
trueif theExceptionmay have a stack trace attached to itsstackproperty, otherwisefalse. Defaults tofalse.
Exceptions
TypeError-
The
payloadandtagsequences do not have the same number of elements and/or the elements are not of matching types.
Description
The Exception() constructor accepts a WebAssembly.Tag, an array of values, and an options object as arguments.
The tag uniquely defines the type of an exception, including the order of its arguments and their data types.
The same tag that was used to create the Exception is required to access the arguments of a thrown exception (using Exception.prototype.getArg()).
Examples
>Basic usage
You would not normally use this contructor to manually create a Wasm exception. Instead, a WebAssembly.Exception object is normally created when handling Wasm exceptions, for example:
WebAssembly.instantiateStreaming(fetch("module.wasm"), { env }).then(
(result) => {
try {
// Cause function to throw
result.instance.exports.throw(-1);
} catch (e) {
if (e instanceof WebAssembly.Exception && e.is(myErrorTag)) {
const errorCode = e.getArg(myErrorTag, 0); // 0 = first payload value
console.log("Error code:", errorCode); // 42
} else {
throw e; // throw other errors
}
}
},
);
For a working example, see the throw instruction reference page.
Manual usage
This example shows manual creation of an WebAssembly.Exception instance.
// Create tag and use it to create an exception
const tag = new WebAssembly.Tag({ parameters: ["i32", "f32"] });
const exception = new WebAssembly.Exception(tag, [42, 42.3]);
Note:
The stack example shows the creation of an exception that uses the options parameter.
Specifications
| Specification |
|---|
| WebAssembly JavaScript Interface: Exception Handling> # dom-exception-exception> |