From 1ddd95504b4507beeda0f08bd772eb167922b86a Mon Sep 17 00:00:00 2001 From: Claas Augner <495429+caugner@users.noreply.github.com> Date: Fri, 22 May 2026 17:48:27 +0200 Subject: [PATCH 1/3] Use jsxref shortform for null, this, delete, new, instanceof (#44221) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(redirects): add jsxref shortcut redirects for operators Adds `Reference/{null,this,delete,new,instanceof}` → `Reference/Operators/{...}` so `{{jsxref("name")}}` shortform resolves directly via the first lookup path in `jsxref`. * refactor: collapse jsxref operator longforms to shortform Replaces `{{jsxref("Operators/X", "X")}}` with `{{jsxref("X")}}` for `null`, `this`, `delete`, `new`, and `instanceof` across 66 files. Resolution now goes through the `Reference/X` redirects added in the prior commit and the `Reference` slug index in rari@jsxref-with-index. Longforms with custom display text (e.g. `"delete x"`, `"deleted"`, `"x instanceof y"`) are preserved as-is. --- files/en-us/_redirects.txt | 5 +++++ files/en-us/glossary/binding/index.md | 2 +- .../core/scripting/object_basics/index.md | 2 +- files/en-us/mozilla/firefox/releases/38/index.md | 2 +- files/en-us/mozilla/firefox/releases/40/index.md | 2 +- files/en-us/mozilla/firefox/releases/44/index.md | 2 +- files/en-us/web/api/domtokenlist/foreach/index.md | 2 +- .../web/api/eventtarget/addeventlistener/index.md | 2 +- .../largestcontentfulpaint/presentationtime/index.md | 2 +- .../presentationtime/index.md | 2 +- .../presentationtime/index.md | 2 +- .../performancepainttiming/presentationtime/index.md | 2 +- files/en-us/web/api/windowclient/navigate/index.md | 2 +- .../web/javascript/guide/meta_programming/index.md | 2 +- files/en-us/web/javascript/index.md | 2 +- .../en-us/web/javascript/reference/classes/index.md | 2 +- .../web/javascript/reference/classes/static/index.md | 2 +- .../reference/errors/bad_new_optional/index.md | 4 ++-- .../reference/errors/bad_super_call/index.md | 2 +- .../reference/errors/builtin_ctor_no_new/index.md | 4 ++-- .../reference/errors/class_ctor_no_new/index.md | 4 ++-- .../reference/errors/invalid_derived_return/index.md | 2 +- .../reference/errors/super_not_called/index.md | 2 +- .../web/javascript/reference/functions/get/index.md | 2 +- .../web/javascript/reference/functions/set/index.md | 2 +- .../reference/global_objects/array/foreach/index.md | 2 +- .../reference/global_objects/bigint/bigint/index.md | 2 +- .../reference/global_objects/error/error/index.md | 2 +- .../reference/global_objects/error/index.md | 2 +- .../global_objects/function/arguments/index.md | 2 +- .../reference/global_objects/function/bind/index.md | 12 ++++++------ .../global_objects/function/caller/index.md | 2 +- .../reference/global_objects/globalthis/index.md | 2 +- .../web/javascript/reference/global_objects/index.md | 2 +- .../reference/global_objects/iterator/from/index.md | 2 +- .../reference/global_objects/object/index.md | 2 +- .../global_objects/object/isprototypeof/index.md | 4 ++-- .../reference/global_objects/object/proto/index.md | 4 ++-- .../global_objects/proxy/proxy/construct/index.md | 8 ++++---- .../proxy/proxy/deleteproperty/index.md | 8 ++++---- .../proxy/proxy/getprototypeof/index.md | 2 +- .../reference/global_objects/proxy/proxy/index.md | 4 ++-- .../global_objects/reflect/construct/index.md | 4 ++-- .../global_objects/reflect/deleteproperty/index.md | 2 +- .../reference/global_objects/set/difference/index.md | 2 +- .../javascript/reference/global_objects/set/index.md | 2 +- .../global_objects/set/intersection/index.md | 2 +- .../global_objects/set/isdisjointfrom/index.md | 2 +- .../reference/global_objects/set/issubsetof/index.md | 2 +- .../global_objects/set/issupersetof/index.md | 2 +- .../global_objects/set/symmetricdifference/index.md | 2 +- .../reference/global_objects/set/union/index.md | 2 +- .../sharedarraybuffer/sharedarraybuffer/index.md | 2 +- .../reference/global_objects/string/index.md | 2 +- .../global_objects/symbol/hasinstance/index.md | 4 ++-- .../reference/global_objects/symbol/index.md | 6 +++--- .../reference/global_objects/symbol/symbol/index.md | 2 +- files/en-us/web/javascript/reference/index.md | 8 ++++---- .../javascript/reference/lexical_grammar/index.md | 10 +++++----- .../javascript/reference/operators/grouping/index.md | 2 +- .../web/javascript/reference/operators/index.md | 10 +++++----- .../reference/operators/operator_precedence/index.md | 4 ++-- .../reference/operators/optional_chaining/index.md | 2 +- .../reference/operators/spread_syntax/index.md | 2 +- .../web/javascript/reference/operators/this/index.md | 2 +- .../javascript/reference/operators/typeof/index.md | 2 +- .../web/javascript/reference/statements/var/index.md | 2 +- 67 files changed, 104 insertions(+), 99 deletions(-) diff --git a/files/en-us/_redirects.txt b/files/en-us/_redirects.txt index 207afe5ea365e5e..314eded985ebbee 100644 --- a/files/en-us/_redirects.txt +++ b/files/en-us/_redirects.txt @@ -15528,9 +15528,14 @@ /en-US/docs/Web/JavaScript/Reference/Symbols /en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol /en-US/docs/Web/JavaScript/Reference/arrow_functions /en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions /en-US/docs/Web/JavaScript/Reference/default_parameters /en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters +/en-US/docs/Web/JavaScript/Reference/delete /en-US/docs/Web/JavaScript/Reference/Operators/delete /en-US/docs/Web/JavaScript/Reference/eval /en-US/docs/Web/JavaScript/Reference/Global_Objects/eval +/en-US/docs/Web/JavaScript/Reference/instanceof /en-US/docs/Web/JavaScript/Reference/Operators/instanceof +/en-US/docs/Web/JavaScript/Reference/new /en-US/docs/Web/JavaScript/Reference/Operators/new +/en-US/docs/Web/JavaScript/Reference/null /en-US/docs/Web/JavaScript/Reference/Operators/null /en-US/docs/Web/JavaScript/Reference/rest_parameters /en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters /en-US/docs/Web/JavaScript/Reference/template_strings /en-US/docs/Web/JavaScript/Reference/Template_literals +/en-US/docs/Web/JavaScript/Reference/this /en-US/docs/Web/JavaScript/Reference/Operators/this /en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript /en-US/docs/Web/Security/Defenses/Same-origin_policy /en-US/docs/Web/JavaScript/Shells /en-US/docs/Web/JavaScript/Reference/JavaScript_technologies_overview /en-US/docs/Web/JavaScript/The_performance_hazards_of__[[Prototype]]_mutation /en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/setPrototypeOf diff --git a/files/en-us/glossary/binding/index.md b/files/en-us/glossary/binding/index.md index ecaddc20f72455c..f84d3c3ad11ce5a 100644 --- a/files/en-us/glossary/binding/index.md +++ b/files/en-us/glossary/binding/index.md @@ -5,7 +5,7 @@ page-type: glossary-definition sidebar: glossarysidebar --- -In programming, a **binding** is an association of an {{glossary("identifier")}} with a value. Not all bindings are {{glossary("variable", "variables")}} — for example, function {{glossary("parameter", "parameters")}} and the binding created by the {{jsxref("Statements/try...catch", "catch (e)")}} block are not "variables" in the strict sense. In addition, some bindings are implicitly created by the language — for example, {{jsxref("Operators/this", "this")}} and [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) in JavaScript. +In programming, a **binding** is an association of an {{glossary("identifier")}} with a value. Not all bindings are {{glossary("variable", "variables")}} — for example, function {{glossary("parameter", "parameters")}} and the binding created by the {{jsxref("Statements/try...catch", "catch (e)")}} block are not "variables" in the strict sense. In addition, some bindings are implicitly created by the language — for example, {{jsxref("this")}} and [`new.target`](/en-US/docs/Web/JavaScript/Reference/Operators/new.target) in JavaScript. A binding is {{glossary("mutable")}} if it can be re-assigned, and {{glossary("immutable")}} otherwise; this does _not_ mean that the value it holds is immutable. diff --git a/files/en-us/learn_web_development/core/scripting/object_basics/index.md b/files/en-us/learn_web_development/core/scripting/object_basics/index.md index f81237ea33dbecd..b286f15edf3fe76 100644 --- a/files/en-us/learn_web_development/core/scripting/object_basics/index.md +++ b/files/en-us/learn_web_development/core/scripting/object_basics/index.md @@ -348,7 +348,7 @@ frankie.introduceSelf(); // "Hi! I'm Frankie." ``` -This works fine but is a bit long-winded: we have to create an empty object, initialize it, and return it. A better way is to use a **constructor**. A constructor is just a function called using the {{jsxref("operators/new", "new")}} keyword. When you call a constructor, it will: +This works fine but is a bit long-winded: we have to create an empty object, initialize it, and return it. A better way is to use a **constructor**. A constructor is just a function called using the {{jsxref("new")}} keyword. When you call a constructor, it will: - create a new object - bind `this` to the new object, so you can refer to `this` in your constructor code diff --git a/files/en-us/mozilla/firefox/releases/38/index.md b/files/en-us/mozilla/firefox/releases/38/index.md index 0d9c120701fc9ad..82830a261f882db 100644 --- a/files/en-us/mozilla/firefox/releases/38/index.md +++ b/files/en-us/mozilla/firefox/releases/38/index.md @@ -61,7 +61,7 @@ Highlights: - Duplicated parameter name is no longer allowed when rest-parameter is present ([Firefox bug 1096376](https://bugzil.la/1096376)). - Duplicated parameter name is no longer allowed in arrow functions ([Firefox bug 1096377](https://bugzil.la/1096377)). - Duplicated parameter name is no longer allowed in concise method definitions ([Firefox bug 1096378](https://bugzil.la/1096378)). -- Warning is shown when {{jsxref("Map")}}/{{jsxref("Set")}}/{{jsxref("WeakMap")}} constructor is called without {{jsxref("Operators/new", "new")}} ([Firefox bug 1108930](https://bugzil.la/1108930)). +- Warning is shown when {{jsxref("Map")}}/{{jsxref("Set")}}/{{jsxref("WeakMap")}} constructor is called without {{jsxref("new")}} ([Firefox bug 1108930](https://bugzil.la/1108930)). - The {{jsxref("WeakMap.get", "get")}}, {{jsxref("WeakMap.has", "has")}}, and {{jsxref("WeakMap.delete", "delete")}} methods of {{jsxref("WeakMap")}} objects no longer throw when the `key` parameter is not an object ([Firefox bug 1127827](https://bugzil.la/1127827)). - The optional and non-standard second `fallback` parameter for {{jsxref("WeakMap.prototype.get()")}} has been removed ([Firefox bug 1127827](https://bugzil.la/1127827)). - When defining a [generator method](/en-US/docs/Web/JavaScript/Reference/Functions/Method_definitions), `set` and `get` are no longer invalid names ([Firefox bug 1073809](https://bugzil.la/1073809)). diff --git a/files/en-us/mozilla/firefox/releases/40/index.md b/files/en-us/mozilla/firefox/releases/40/index.md index 0f8fa77f79acf43..9358602c2cc29f4 100644 --- a/files/en-us/mozilla/firefox/releases/40/index.md +++ b/files/en-us/mozilla/firefox/releases/40/index.md @@ -56,7 +56,7 @@ _No change._ - Unreachable code after {{jsxref("Statements/return", "return")}} statement (including unreachable expression after {{jsxref("Statements/return", "semicolon-less return statements", "#Automatic_semicolon_insertion", 1)}}) will now show a warning in the console ([Firefox bug 1005110](https://bugzil.la/1005110), [Firefox bug 1151931](https://bugzil.la/1151931)). - {{jsxref("Symbol.match")}} has been added ([Firefox bug 1054755](https://bugzil.la/1054755)). - Passing an object which has a property named {{jsxref("Symbol.match")}} with a {{Glossary("truthy")}} value to {{jsxref("String.prototype.startsWith")}}, {{jsxref("String.prototype.endsWith")}}, and `String.prototype.contains` now throws a {{jsxref("TypeError")}} ([Firefox bug 1054755](https://bugzil.la/1054755)). -- {{jsxref("RegExp")}} function returns pattern itself if called without {{jsxref("Operators/new", "new")}} and pattern object has a property named {{jsxref("Symbol.match")}} with a {{Glossary("truthy")}} value, and the pattern object's `constructor` property equals to {{jsxref("RegExp")}} function. ([Firefox bug 1147817](https://bugzil.la/1147817)). +- {{jsxref("RegExp")}} function returns pattern itself if called without {{jsxref("new")}} and pattern object has a property named {{jsxref("Symbol.match")}} with a {{Glossary("truthy")}} value, and the pattern object's `constructor` property equals to {{jsxref("RegExp")}} function. ([Firefox bug 1147817](https://bugzil.la/1147817)). - Support for the non-standard JS1.7 destructuring for-in has been dropped ([Firefox bug 1083498](https://bugzil.la/1083498)). - [Non-standard initializer expressions](/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_for-in_initializer) in [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loops are now ignored and will present a warning in the console. ([Firefox bug 748550](https://bugzil.la/748550) and [Firefox bug 1164741](https://bugzil.la/1164741)). - [`\u{xxxxxx}`](/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#unicode_code_point_escapes) Unicode code point escapes have been added ([Firefox bug 320500](https://bugzil.la/320500)). diff --git a/files/en-us/mozilla/firefox/releases/44/index.md b/files/en-us/mozilla/firefox/releases/44/index.md index 918e17b52d961d0..74f88be6705c721 100644 --- a/files/en-us/mozilla/firefox/releases/44/index.md +++ b/files/en-us/mozilla/firefox/releases/44/index.md @@ -83,7 +83,7 @@ Highlights: #### Changes - The [`let`](/en-US/docs/Web/JavaScript/Reference/Statements/let) and [`const`](/en-US/docs/Web/JavaScript/Reference/Statements/const) bindings in the global level have been made compliant with ES2015 semantics. See [Firefox bug 589199](https://bugzil.la/589199) and the blog post ["Breaking changes in let and const in Firefox Nightly 44"](https://blog.mozilla.org/addons/2015/10/14/breaking-changes-let-const-firefox-nightly-44/). In addition, `let` is now available to default Web JavaScript (strict and non-strict) and does not require a version opt-in anymore ([Firefox bug 932517](https://bugzil.la/932517)). -- If [typed arrays'](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) (like {{jsxref("Int8Array", "Int8Array")}}) and {{jsxref("ArrayBuffer", "ArrayBuffer")}}) constructors are called as a function without the {{jsxref("Operators/new", "new")}} operator, a {{jsxref("TypeError")}} is now thrown as per the ES2015 specification ([Firefox bug 980945](https://bugzil.la/980945), [Firefox bug 1214936](https://bugzil.la/1214936)). +- If [typed arrays'](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) (like {{jsxref("Int8Array", "Int8Array")}}) and {{jsxref("ArrayBuffer", "ArrayBuffer")}}) constructors are called as a function without the {{jsxref("new")}} operator, a {{jsxref("TypeError")}} is now thrown as per the ES2015 specification ([Firefox bug 980945](https://bugzil.la/980945), [Firefox bug 1214936](https://bugzil.la/1214936)). - The {{jsxref("RegExp")}} sticky flag now follows the ES2015 standard for [anchored sticky regular expressions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky#anchored_sticky_flag) ([Firefox bug 773687](https://bugzil.la/773687)). - The JavaScript shell (SpiderMonkey's REPL) now defaults to the default, Web-compatible JS version (and not JS1.7+ anymore) ([Firefox bug 1192329](https://bugzil.la/1192329)). diff --git a/files/en-us/web/api/domtokenlist/foreach/index.md b/files/en-us/web/api/domtokenlist/foreach/index.md index 592b97282ebc91a..d0ed3c586aa0374 100644 --- a/files/en-us/web/api/domtokenlist/foreach/index.md +++ b/files/en-us/web/api/domtokenlist/foreach/index.md @@ -31,7 +31,7 @@ forEach(callback, thisArg) - : The array that `forEach()` is being applied to. - `thisArg` {{Optional_inline}} - - : The value to use as {{jsxref("Operators/this", "this")}} when executing `callback`. + - : The value to use as {{jsxref("this")}} when executing `callback`. ### Return value diff --git a/files/en-us/web/api/eventtarget/addeventlistener/index.md b/files/en-us/web/api/eventtarget/addeventlistener/index.md index e94c3a4d237b3c6..b2e93b859f65335 100644 --- a/files/en-us/web/api/eventtarget/addeventlistener/index.md +++ b/files/en-us/web/api/eventtarget/addeventlistener/index.md @@ -135,7 +135,7 @@ It is often desirable to reference the element on which the event handler was fi such as when using a generic handler for a set of similar elements. When attaching a handler function to an element using `addEventListener()`, -the value of {{jsxref("Operators/this","this")}} inside the handler will be a reference to +the value of {{jsxref("this")}} inside the handler will be a reference to the element. It will be the same as the value of the `currentTarget` property of the event argument that is passed to the handler. diff --git a/files/en-us/web/api/largestcontentfulpaint/presentationtime/index.md b/files/en-us/web/api/largestcontentfulpaint/presentationtime/index.md index 01fbebb8a136b4f..f131a63c6d8e70b 100644 --- a/files/en-us/web/api/largestcontentfulpaint/presentationtime/index.md +++ b/files/en-us/web/api/largestcontentfulpaint/presentationtime/index.md @@ -14,7 +14,7 @@ The `presentationTime` is optional — some browsers may choose always to return ## Value -A {{domxref("DOMHighResTimeStamp")}} or {{jsxref("Operators/null", "null")}} if the value is not exposed. +A {{domxref("DOMHighResTimeStamp")}} or {{jsxref("null")}} if the value is not exposed. ## Examples diff --git a/files/en-us/web/api/performanceelementtiming/presentationtime/index.md b/files/en-us/web/api/performanceelementtiming/presentationtime/index.md index 9d23d9da611b171..a778e913cbc50db 100644 --- a/files/en-us/web/api/performanceelementtiming/presentationtime/index.md +++ b/files/en-us/web/api/performanceelementtiming/presentationtime/index.md @@ -16,7 +16,7 @@ The `presentationTime` is optional — some browsers may choose always to return ## Value -A {{domxref("DOMHighResTimeStamp")}} or {{jsxref("Operators/null", "null")}} if the value is not exposed. +A {{domxref("DOMHighResTimeStamp")}} or {{jsxref("null")}} if the value is not exposed. ## Examples diff --git a/files/en-us/web/api/performancelonganimationframetiming/presentationtime/index.md b/files/en-us/web/api/performancelonganimationframetiming/presentationtime/index.md index 183c3afd6e269c7..1a4831789c8eb8f 100644 --- a/files/en-us/web/api/performancelonganimationframetiming/presentationtime/index.md +++ b/files/en-us/web/api/performancelonganimationframetiming/presentationtime/index.md @@ -16,7 +16,7 @@ The `presentationTime` is optional — some browsers may choose always to return ## Value -A {{domxref("DOMHighResTimeStamp")}} or {{jsxref("Operators/null", "null")}} if the value is not exposed. +A {{domxref("DOMHighResTimeStamp")}} or {{jsxref("null")}} if the value is not exposed. ## Examples diff --git a/files/en-us/web/api/performancepainttiming/presentationtime/index.md b/files/en-us/web/api/performancepainttiming/presentationtime/index.md index 03afa9af5a10e43..00f6b8f5d3c49d1 100644 --- a/files/en-us/web/api/performancepainttiming/presentationtime/index.md +++ b/files/en-us/web/api/performancepainttiming/presentationtime/index.md @@ -14,7 +14,7 @@ The `presentationTime` is optional — some browsers may choose always to return ## Value -A {{domxref("DOMHighResTimeStamp")}} or {{jsxref("Operators/null", "null")}} if the value is not exposed. +A {{domxref("DOMHighResTimeStamp")}} or {{jsxref("null")}} if the value is not exposed. ## Examples diff --git a/files/en-us/web/api/windowclient/navigate/index.md b/files/en-us/web/api/windowclient/navigate/index.md index d54d3d342dc1b66..31a75d0aa81b43c 100644 --- a/files/en-us/web/api/windowclient/navigate/index.md +++ b/files/en-us/web/api/windowclient/navigate/index.md @@ -25,7 +25,7 @@ navigate(url) ### Return value -A {{jsxref("Promise")}} that resolves to the existing {{domxref("WindowClient")}} if the URL is from the same origin as the service worker, or {{jsxref("Operators/null", "null")}} otherwise. +A {{jsxref("Promise")}} that resolves to the existing {{domxref("WindowClient")}} if the URL is from the same origin as the service worker, or {{jsxref("null")}} otherwise. ## Specifications diff --git a/files/en-us/web/javascript/guide/meta_programming/index.md b/files/en-us/web/javascript/guide/meta_programming/index.md index eee1d41dc950d2e..206b2c81ecb8e56 100644 --- a/files/en-us/web/javascript/guide/meta_programming/index.md +++ b/files/en-us/web/javascript/guide/meta_programming/index.md @@ -59,7 +59,7 @@ The following table summarizes the available traps available to `Proxy` objects. {{jsxref("Proxy/Proxy/getPrototypeOf", "handler.getPrototypeOf()")}}
new x(y)new x(y)new xnew x`. If not, we write the error object to the output `
`. + +```js live-sample___tag_definition +wasm.then((result) => { + myErrorTag = result.instance.exports.my_error; + try { + result.instance.exports.might_throw(-1); + } catch (error) { + if (error instanceof WebAssembly.Exception && error.is(myErrorTag)) { + output.textContent = `Error code: ${error.getArg(myErrorTag, 0)}`; + } else { + output.textContent = `Error: ${error}`; // report other errors + } + } +}); +``` + +#### Result + +{{embedlivesample("tag_definition", "100%", 60)}} + +## Specifications + +{{Specifications}} + +## Browser compatibility + +{{Compat}} + +## See also + +- [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction +- [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction +- [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) instruction + - [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) clause + - [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) clause + - [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) clause + - [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) clause +- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type +- [`WebAssembly.Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) JavaScript interface +- [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) JavaScript interface diff --git a/files/en-us/webassembly/reference/exception_handling/index.md b/files/en-us/webassembly/reference/exception_handling/index.md new file mode 100644 index 000000000000000..0b13f4491e115f2 --- /dev/null +++ b/files/en-us/webassembly/reference/exception_handling/index.md @@ -0,0 +1,38 @@ +--- +title: WebAssembly exception handling instructions +slug: WebAssembly/Reference/Exception_handling +page-type: landing-page +sidebar: webassemblysidebar +--- + +WebAssembly exception handling instructions. + +## Throw + +- [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) + - : Throws an exception of a specified type, as defined by a [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition. +- [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) + - : Rethrows a previously-thrown exception represented by an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value. + +## Try + +- [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) + - : Enables you to test a block of code to see whether it throws an exception, handling the exception with a [catch clause](#catch_clauses) clause if so. + +### Catch clauses + +- [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) + - : Catches exceptions matching a specified error `tag`, pushing the exception payload to the stack. +- [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) + - : Catches any exception and pushes nothing to the stack. +- [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) + - : Catches exceptions matching a specified error `tag`, pushing the exception payload and an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the exception to the stack. +- [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) + - : Catches any exception and pushes an `exnref` value representing the exception to the stack. + +## See also + +- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type +- [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition +- [`WebAssembly.Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) JavaScript interface +- [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) JavaScript interface diff --git a/files/en-us/webassembly/reference/exception_handling/throw/index.md b/files/en-us/webassembly/reference/exception_handling/throw/index.md new file mode 100644 index 000000000000000..7d8a83920633c64 --- /dev/null +++ b/files/en-us/webassembly/reference/exception_handling/throw/index.md @@ -0,0 +1,105 @@ +--- +title: "throw: Wasm exception handling instruction" +short-title: throw +slug: WebAssembly/Reference/Exception_handling/throw +page-type: webassembly-instruction +browser-compat: webassembly.instructions.throw +sidebar: webassemblysidebar +--- + +The **`throw`** [exception handling](/en-US/docs/WebAssembly/Reference/Exception_handling) instruction throws an exception of a specified type, as defined by a [tag](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition. + +{{InteractiveExample("Wat Demo: throw", "tabbed-taller")}} + +```wat interactive-example +(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)) +) +``` + +```js interactive-example +// 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 + +```plain +throw identifier +``` + +- `throw` + - : The `throw` instruction. +- `identifier` + - : An identifier for the exception tag type to throw. This can be: + - An identifying name, as defined by the [`identifier`](/en-US/docs/WebAssembly/Reference/Definitions/tag#identifier) of the corresponding tag type. + - A tag index number — `0` to identify the first specified tag, `1` for the second, etc. + +### Type + +```plain +[payload1, payload2, payloadN] -> [] +``` + +- `payload` values + - : 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`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) and [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref), or in JavaScript via a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) statement. + +See the [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/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` | + +## See also + +- [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction +- [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) instruction + - [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) clause + - [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) clause + - [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) clause + - [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) clause +- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type +- [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition diff --git a/files/en-us/webassembly/reference/exception_handling/throw_ref/index.md b/files/en-us/webassembly/reference/exception_handling/throw_ref/index.md new file mode 100644 index 000000000000000..c7dbec7b99946e5 --- /dev/null +++ b/files/en-us/webassembly/reference/exception_handling/throw_ref/index.md @@ -0,0 +1,123 @@ +--- +title: "throw_ref: Wasm exception handling instruction" +short-title: throw_ref +slug: WebAssembly/Reference/Exception_handling/throw_ref +page-type: webassembly-instruction +browser-compat: webassembly.instructions.throw_ref +sidebar: webassemblysidebar +--- + +The **`throw_ref`** [exception handling](/en-US/docs/WebAssembly/Reference/Exception_handling) instruction rethrows a previously-thrown exception represented by an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value. + +{{InteractiveExample("Wat Demo: throw_ref", "tabbed-taller")}} + +```wat interactive-example +(module + ;; Import error tag + (tag $my_error (import "env" "my_error") (param i32)) + + (func $try_and_rethrow (param $value i32) + ;; Define a variable to store an exnref + (local $err exnref) + + (block $handler (result i32 exnref) + (try_table (catch_ref $my_error $handler) + (call $might_throw (local.get $value)) + ) + (return) + ) + + ;; catch_ref returns error value and exnref + ;; Stack is now: i32, exnref (exnref on top) + (local.set $err) ;; pop exnref + (drop) ;; drop the i32 payload + (local.get $err) ;; push exnref back + (throw_ref) + ) + + ;; Function that throws an error of type $my_error + ;; when its parameter is less than 0 + (func $might_throw (param $value i32) + (local.get $value) + (i32.const 0) + (i32.lt_s) + (if + (then + (i32.const 42) + (throw $my_error) + ) + ) + ) + + (export "try_and_rethrow" (func $try_and_rethrow)) +) +``` + +```js interactive-example +// 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.try_and_rethrow(-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 + +```plain +throw_ref +``` + +- `throw_ref` + - : The `throw_ref` instruction. + +### Type + +```plain +[exception] -> [] +``` + +- `exception` + - : The exception to rethrow, which must be an `exnref` value. + +### Binary encoding + +| Instruction | Binary format | Example text => binary | +| ----------- | ------------- | ---------------------- | +| `throw_ref` | `0x0a` | `throw_ref` => `0x0a` | + +## Description + +A `throw_ref` instruction can be used to rethrow a previously-thrown exception, as represented by an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value. Values of type `exnref` are pushed onto the stack by [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) and [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) clauses. + +Generally, rethrowing exceptions is useful because you might want to perform an action such as cleanup or logging but then still let users know that an error ocurred. + +## See also + +- [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction +- [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) instruction + - [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) clause + - [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) clause + - [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) clause + - [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) clause +- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type +- [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition diff --git a/files/en-us/webassembly/reference/exception_handling/try_table/catch/index.md b/files/en-us/webassembly/reference/exception_handling/try_table/catch/index.md new file mode 100644 index 000000000000000..53edd90adb963cc --- /dev/null +++ b/files/en-us/webassembly/reference/exception_handling/try_table/catch/index.md @@ -0,0 +1,143 @@ +--- +title: "catch: try_table clause" +short-title: catch +slug: WebAssembly/Reference/Exception_handling/try_table/catch +page-type: webassembly-instruction +browser-compat: webassembly.instructions.try_table.catch +sidebar: webassemblysidebar +--- + +The **`catch`** clause catches exceptions matching a specified error [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag), pushing the exception payload to the stack. + +{{InteractiveExample("Wat Demo: catch", "tabbed-taller")}} + +```wat interactive-example +(module + ;; Import error tag and console.log + (tag $my_error (import "env" "my_error") (param i32)) + (import "env" "log" (func $log (param i32))) + + (func $try_and_catch (param $value i32) + (block $handler (result i32) + ;; In try_table block, catch thrown exception of type $my_error + (try_table (catch $my_error $handler) + (call $might_throw (local.get $value)) + ) + (return) + ) + ;; Log value returned by handler block + call $log + ) + + ;; Function that throws an error of type $my_error + ;; when its parameter is less than 0 + (func $might_throw (param $value i32) + (local.get $value) + (i32.const 0) + (i32.lt_s) + (if + (then + ;; Throw exception with payload of 42 + (i32.const 42) + (throw $my_error) + ) + ) + ) + + (export "try_and_catch" (func $try_and_catch)) +) + +``` + +```js interactive-example +// Define error tag in JS +const myErrorTag = new WebAssembly.Tag({ parameters: ["i32"] }); + +// Import error tag and console.log into the module +const env = { + my_error: myErrorTag, // import the tag into the module + log: console.log, +}; + +WebAssembly.instantiateStreaming(fetch("{%wasm-url%}"), { env }).then( + // Negative value causes function to throw + (result) => result.instance.exports.try_and_catch(-1), +); +``` + +## Syntax + +```plain +catch tag_identifier block_identifier +``` + +- `catch` + - : The `catch` clause. +- `tag_identifier` + - : The identifier for the exception type to catch. This can be: + - An identifying name, as defined by the [`identifier`](/en-US/docs/WebAssembly/Reference/Definitions/tag#identifier) of the corresponding tag type. + - A tag index number — `0` to identify the first specified tag, `1` for the second, etc. +- `block_identifier` + - : The identifier for the [`block`](/en-US/docs/WebAssembly/Reference/Control_flow/block) to branch to when the exception is caught. This can be: + - An identifying name, as defined by the identifier of the corresponding block. + - A block index number — `0` to identify the innermost block, `1` for the next innermost, etc. + +### Type + +```plain +[] -> [payload*] +``` + +- `payload*` + - : Zero or more payload values created by the thrown exception, which typically represent identifying error codes. + +These values are not pushed onto the stack directly at the site of the `catch` clause, rather they are pushed onto the stack at the site of the block branched to when the exception is thrown. + +### Binary encoding + +| Clause | Catch type byte | +| ------- | --------------- | +| `catch` | `0x00` | + +`catch` is not a standalone instruction — instead, it is encoded as a clause within a `try_table` instruction with a byte of `0x00`. A `try_table` with a single `catch` clause: + +```wat +(try_table (catch $my_error $handler) ... ) +``` + +would be encoded like this: + +```plain +... 0x01 0x00 0x00 0x00 ... +``` + +## Description + +The `catch` clause can be included inside a [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) block to catch exceptions with a specific error [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag). When such an exception is thrown, the code branches to the specified `block`, at which point the exception's payload values are pushed to the stack. + +`catch` is useful when you don't need to rethrow an exception, but you do want to report that a specific exception type has been thrown. + +The referenced block must declare a result type that matches the exception's payload. In the example shown earlier, the exception type is defined with a single `i32` parameter in its `tag` definition: + +```wat +(tag $my_error (import "env" "my_error") (param i32)) +``` + +When the exception is caught, the block branched to specifies the same data type for its `result`: + +```wat +(block $handler (result i32) + ... +) +``` + +## See also + +- [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction +- [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction +- [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) instruction + - [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) clause + - [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) clause + - [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) clause +- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type +- [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition diff --git a/files/en-us/webassembly/reference/exception_handling/try_table/catch_all/index.md b/files/en-us/webassembly/reference/exception_handling/try_table/catch_all/index.md new file mode 100644 index 000000000000000..08a4e5dc5e65cd4 --- /dev/null +++ b/files/en-us/webassembly/reference/exception_handling/try_table/catch_all/index.md @@ -0,0 +1,128 @@ +--- +title: "catch_all: try_table clause" +short-title: catch_all +slug: WebAssembly/Reference/Exception_handling/try_table/catch_all +page-type: webassembly-instruction +browser-compat: webassembly.instructions.try_table.catch_all +sidebar: webassemblysidebar +--- + +The **`catch_all`** clause catches any exception and pushes nothing to the stack. + +{{InteractiveExample("Wat Demo: catch_all", "tabbed-taller")}} + +```wat interactive-example +(module + ;; Import the error tag and the log function + (tag $my_error (import "env" "my_error") (param i32)) + (import "env" "log" (func $log)) + + (func $try_and_catch (param $value i32) + ;; catch_all catches any exception thrown + (block $handler + (try_table (catch_all $handler) + (call $might_throw (local.get $value)) + ) + (return) + ) + ;; Call log to notify user that exception has been thrown + call $log + ) + + ;; Function that throws an error of type $my_error + ;; when its parameter is less than 0 + (func $might_throw (param $value i32) + (local.get $value) + (i32.const 0) + (i32.lt_s) + (if + (then + (i32.const 42) + (throw $my_error) + ) + ) + ) + + (export "try_and_catch" (func $try_and_catch)) +) +``` + +```js interactive-example +// Define error tag in JS +const myErrorTag = new WebAssembly.Tag({ parameters: ["i32"] }); + +// Import the tag and the log function into the module +const env = { + my_error: myErrorTag, + log: () => { + console.log("An error was caught!"); + }, +}; + +WebAssembly.instantiateStreaming(fetch("{%wasm-url%}"), { env }).then( + // Negative value causes function to throw + (result) => result.instance.exports.try_and_catch(-1), +); +``` + +## Syntax + +```plain +catch_all block_identifier +``` + +- `catch_all` + - : The `catch_all` clause. +- `block_identifier` + - : The identifier for the [`block`](/en-US/docs/WebAssembly/Reference/Control_flow/block) to branch to when the exception is caught. This can be: + - An identifying name, as defined by the identifier of the corresponding block. + - A block index number — `0` to identify the innermost block, `1` for the next innermost, etc. + +### Type + +```plain +[] -> [] +``` + +### Binary encoding + +| Clause | catch_all type byte | +| ----------- | ------------------- | +| `catch_all` | `0x02` | + +`catch_all` is not a standalone clause — instead, it is encoded as a clause within a `try_table` instruction with a byte of `0x02`. A `try_table` with a single `catch_all` clause: + +```wat +(try_table (catch_all $handler) ... ) +``` + +would be encoded like this: + +```plain +... 0x01 0x02 0x00 ... +``` + +## Description + +The `catch_all` clause can be included inside a [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) block to catch any thrown exceptions. When an exception is thrown, the code branches to the specified `block`. + +`catch_all` is useful when you don't need to rethrow an exception, and you don't want to catch a specific exception, but you do want to report that an exception of some kind has been thrown. + +In the case of `catch_all`, the referenced block doesn't need to declare a result type that matches the exception's payload, because no result is pushed to the stack. In the example shown earlier, the `block` has no result type declared: + +```wat +(block $handler + ... +) +``` + +## See also + +- [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction +- [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction +- [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) instruction + - [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) clause + - [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) clause + - [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) clause +- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type +- [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition diff --git a/files/en-us/webassembly/reference/exception_handling/try_table/catch_all_ref/index.md b/files/en-us/webassembly/reference/exception_handling/try_table/catch_all_ref/index.md new file mode 100644 index 000000000000000..c2de1a83b3b786b --- /dev/null +++ b/files/en-us/webassembly/reference/exception_handling/try_table/catch_all_ref/index.md @@ -0,0 +1,142 @@ +--- +title: "catch_all_ref: try_table clause" +short-title: catch_all_ref +slug: WebAssembly/Reference/Exception_handling/try_table/catch_all_ref +page-type: webassembly-instruction +browser-compat: webassembly.instructions.try_table.catch_all_ref +sidebar: webassemblysidebar +--- + +The **`catch_all_ref`** clause catches any exception and pushes an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the exception to the stack. + +{{InteractiveExample("Wat Demo: catch_all_ref", "tabbed-taller")}} + +```wat interactive-example +(module + ;; Import the error tag and the log function + (tag $my_error (import "env" "my_error") (param i32)) + (import "env" "log" (func $log)) + + (func $try_and_catch (param $value i32) + ;; Define a variable to store an exnref + (local $err exnref) + ;; catch_all_ref catches any exception thrown and pushes an exnref + (block $handler (result exnref) + (try_table (catch_all_ref $handler) + (call $might_throw (local.get $value)) + ) + (return) + ) + ;; Save exnref before calling log to notify user + ;; that exception has been thrown + (local.set $err) + (call $log) + ;; Restore exnref + (local.get $err) + ;; rethrow original exception + (throw_ref) + ) + + ;; Function that throws an error of type $my_error + ;; when its parameter is less than 0 + (func $might_throw (param $value i32) + (local.get $value) + (i32.const 0) + (i32.lt_s) + (if + (then + (i32.const 42) + (throw $my_error) + ) + ) + ) + (export "try_and_catch" (func $try_and_catch)) +) +``` + +```js interactive-example +// Define error tag in JS +const myErrorTag = new WebAssembly.Tag({ parameters: ["i32"] }); + +// Import the tag and the log function into the module +const env = { + my_error: myErrorTag, + log: () => { + console.log("An error was caught!"); + }, +}; + +WebAssembly.instantiateStreaming(fetch("{%wasm-url%}"), { env }).then( + // Negative value causes function to throw + (result) => result.instance.exports.try_and_catch(-1), +); +``` + +## Syntax + +```plain +catch_all_ref block_identifier +``` + +- `catch_all_ref` + - : The `catch_all_ref` clause. +- `block_identifier` + - : The identifier for the [`block`](/en-US/docs/WebAssembly/Reference/Control_flow/block) to branch to when the exception is caught. This can be: + - An identifying name, as defined by the identifier of the corresponding block. + - A block index number — `0` to identify the innermost block, `1` for the next innermost, etc. + +### Type + +```plain +[] -> [exception_ref] +``` + +- `exception_ref` + - : An [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the thrown exception. + +This value is not pushed onto the stack directly at the site of the `catch_all_ref` clause, rather it is pushed onto the stack at the site of the block branched to when the exception is thrown. + +### Binary encoding + +| Clause | catch_all_ref type byte | +| --------------- | ----------------------- | +| `catch_all_ref` | `0x03` | + +`catch_all_ref` is not a standalone instruction — instead, it is encoded as a clause within a `try_table` instruction with a byte of `0x03`. A `try_table` with a single `catch_all_ref` clause: + +```wat +(try_table (catch_all_ref $handler) ... ) +``` + +would be encoded like this: + +```plain +... 0x01 0x03 0x00 ... +``` + +## Description + +The `catch_all_ref` clause can be included inside a [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) block to catch any thrown exceptions. When an exception is thrown, the code branches to the specified `block`, at which point an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the thrown exception is pushed to the stack. + +The exception can then be rethrown using a [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction. + +`catch_all_ref` is useful when you want to report that some kind of exception has been thrown, but you also want to rethrow the exception. You might for example want to perform an action such as cleanup or logging but then still let users know that an error ocurred. + +The referenced block must declare a result type that matches the pushed `exnref`. In the example shown earlier, the block branched to when the exception is caught specifies an `exnref` type in its `result`: + +```wat +(block $handler (result exnref) + ... +) +``` + +## See also + +- [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction +- [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction +- [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) instruction + - [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) clause + - [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) clause + - [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) clause +- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type +- [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition diff --git a/files/en-us/webassembly/reference/exception_handling/try_table/catch_ref/index.md b/files/en-us/webassembly/reference/exception_handling/try_table/catch_ref/index.md new file mode 100644 index 000000000000000..67942b7db53816d --- /dev/null +++ b/files/en-us/webassembly/reference/exception_handling/try_table/catch_ref/index.md @@ -0,0 +1,163 @@ +--- +title: "catch_ref: try_table clause" +short-title: catch_ref +slug: WebAssembly/Reference/Exception_handling/try_table/catch_ref +page-type: webassembly-instruction +browser-compat: webassembly.instructions.try_table.catch_ref +sidebar: webassemblysidebar +--- + +The **`catch_ref`** clause catches exceptions matching a specified error [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag), pushing the exception payload and an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the exception to the stack. + +{{InteractiveExample("Wat Demo: catch_ref", "tabbed-taller")}} + +```wat interactive-example +(module + ;; Import error tag + (tag $my_error (import "env" "my_error") (param i32)) + + (func $try_and_rethrow (param $value i32) + ;; Define a variable to store an exnref + (local $err exnref) + + (block $handler (result i32 exnref) + (try_table (catch_ref $my_error $handler) + (call $might_throw (local.get $value)) + ) + (return) + ) + + ;; catch_ref returns error value and exnref + ;; Stack is now: i32, exnref (exnref on top) + (local.set $err) ;; pop exnref + (drop) ;; drop the i32 payload + (local.get $err) ;; push exnref back + (throw_ref) + ) + + ;; Function that throws an error of type $my_error + ;; when its parameter is less than 0 + (func $might_throw (param $value i32) + (local.get $value) + (i32.const 0) + (i32.lt_s) + (if + (then + (i32.const 42) + (throw $my_error) + ) + ) + ) + + (export "try_and_rethrow" (func $try_and_rethrow)) +) +``` + +```js interactive-example +// 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.try_and_rethrow(-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 + +```plain +catch_ref tag_identifier block_identifier +``` + +- `catch_ref` + - : The `catch_ref` clause. +- `tag_identifier` + - : The identifier for the exception type to catch. This can be: + - An identifying name, as defined by the [`identifier`](/en-US/docs/WebAssembly/Reference/Definitions/tag#identifier) of the corresponding tag type. + - A tag index number — `0` to identify the first specified tag, `1` for the second, etc. +- `block_identifier` + - : The identifier for the [`block`](/en-US/docs/WebAssembly/Reference/Control_flow/block) to branch to when the exception is caught. This can be: + - An identifying name, as defined by the identifier of the corresponding block. + - A block index number — `0` to identify the innermost block, `1` for the next innermost, etc. + +### Type + +```plain +[] -> [payload*, exception_ref] +``` + +- `payload*` + - : Zero or more payload values created by the thrown exception, which typically represent identifying error codes. +- `exception_ref` + - : An [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the thrown exception. + +These values are not pushed onto the stack directly at the site of the `catch_ref` clause, rather they are pushed onto the stack at the site of the block branched to when the exception is thrown. + +### Binary encoding + +| Clause | catch_ref type byte | +| ----------- | ------------------- | +| `catch_ref` | `0x01` | + +`catch_ref` is not a standalone instruction — instead, it is encoded as a clause within a `try_table` instruction with a byte of `0x01`. A `try_table` with a single `catch_ref` clause: + +```wat +(try_table (catch_ref $my_error $handler) ... ) +``` + +would be encoded like this: + +```plain +... 0x01 0x01 0x00 0x00 ... +``` + +## Description + +The `catch_ref` clause can be included inside a [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) block to catch exceptions with a specific error [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag). When such an exception is thrown, the code branches to the specified `block`, at which point the exception's payload values and an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the thrown exception are pushed to the stack. + +The exception can then be rethrown using a [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction. + +`catch_ref` is useful when you want to report that a specific exception type has been thrown, but you also want to rethrow the exception. You might for example want to perform an action such as cleanup or logging but then still let users know that a specific error ocurred. + +The referenced block must declare a result type that matches the exception's payload and the `exnref`. In the example shown earlier, the exception type is defined with a single `i32` parameter in its `tag` definition: + +```wat +(tag $my_error (import "env" "my_error") (param i32)) +``` + +When the exception is caught, the block branched to specifies the same data type for the payload plus an `exnref` type in its `result`: + +```wat +(block $handler (result i32 exnref) + ... +) +``` + +## See also + +- [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction +- [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction +- [`try_table`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table) instruction + - [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) clause + - [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) clause + - [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) clause +- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type +- [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition diff --git a/files/en-us/webassembly/reference/exception_handling/try_table/index.md b/files/en-us/webassembly/reference/exception_handling/try_table/index.md new file mode 100644 index 000000000000000..3b62f3c053912fa --- /dev/null +++ b/files/en-us/webassembly/reference/exception_handling/try_table/index.md @@ -0,0 +1,287 @@ +--- +title: "try_table: Wasm exception handling instruction" +short-title: try_table +slug: WebAssembly/Reference/Exception_handling/try_table +page-type: webassembly-instruction +browser-compat: webassembly.instructions.try_table +sidebar: webassemblysidebar +--- + +The **`try_table`** [exception handling](/en-US/docs/WebAssembly/Reference/Exception_handling) instruction enables you to test a block of code to see whether it throws an exception, handling the exception with a `catch` clause if so. + +{{InteractiveExample("Wat Demo: try_table", "tabbed-taller")}} + +```wat interactive-example +(module + ;; Import error tag and console.log + (tag $my_error (import "env" "my_error") (param i32)) + (import "env" "log" (func $log (param i32))) + + (func $try_and_catch (param $value i32) + (block $handler (result i32) + ;; In try_table block, catch thrown exception + (try_table (catch $my_error $handler) + (call $might_throw (local.get $value)) + ) + (return) + ) + ;; Log value returned by handler block + call $log + ) + + ;; Function that throws an error of type $my_error + ;; when its parameter is less than 0 + (func $might_throw (param $value i32) + (local.get $value) + (i32.const 0) + (i32.lt_s) + (if + (then + ;; Throw exception with payload of 42 + (i32.const 42) + (throw $my_error) + ) + ) + ) + + (export "try_and_catch" (func $try_and_catch)) +) +``` + +```js interactive-example +// Define error tag in JS +const myErrorTag = new WebAssembly.Tag({ parameters: ["i32"] }); + +// Import error tag and console.log into the module +const env = { + my_error: myErrorTag, // import the tag into the module + log: console.log, +}; + +WebAssembly.instantiateStreaming(fetch("{%wasm-url%}"), { env }).then( + // Negative value causes function to throw + (result) => result.instance.exports.try_and_catch(-1), +); +``` + +## Syntax + +```plain +try_table blocktype catch* instruction* +``` + +- `try_table` + - : The `try_table` instruction. +- `blocktype` {{optional_inline}} + - : Specifies one or more parameters that will be passed into the `try_table` block and provided as a result value after the block has run. +- `catch*` + - : One or more `catch` clauses, each representing criteria for catching exceptions, and specifying a [`block`](/en-US/docs/WebAssembly/Reference/Control_flow/block) to branch to as a result. Each clause can be one of the following: + - [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) + - [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) + - [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) + - [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) +- `instruction*` + - : Zero or more instructions to execute inside the try block. + +### Type + +```plain +[param*] -> [result*] +``` + +- `param*` + - : Zero or more param values consumed by the `try_table` block, as declared by the `blocktype`. +- `result*` + - : Zero or more result values produced by the `try_table` block, as declared by the `blocktype`. + +### Binary encoding + +| Instruction | Binary format | +| ----------- | -------------------------------------------------------- | +| `try_table` | `0x1f bt:blocktype n:u32 (ct:catch)^n instruction* 0x0b` | + +A basic `try_table` with a single `catch` clause: + +```wat +(try_table (catch $my_error $handler) + ;; instructions ... +) +``` + +Would be encoded like so: + +```plain +0x1f 0x40 0x01 0x00 0x00 0x00 ...instructions binary... 0x0b +``` + +## Description + +A `try_table` instruction, when combined with `catch` clauses, creates the Wasm equivalent of a JavaScript [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) statement. The instructions inside the `try_table` block are run, and if an exception is thrown that is caught by the available `catch` clauses, the code branches to the specified outer [`block`](/en-US/docs/WebAssembly/Reference/Control_flow/block), and the values produced by the `catch` clause are pushed onto the stack. + +The different `catch` clauses behave as follows: + +- [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) + - : If an exception with a matching tag is thrown, branch to the specified `block`, pushing the payload values onto the stack. +- [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) + - : If any exception is thrown, branch to the specified `block`, pushing nothing onto the stack. +- [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) + - : If an exception with a matching tag is thrown, branch to the specified `block`, pushing the payload values and an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the exception onto the stack. +- [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) + - : If any exception is thrown, branch to the specified `block`, pushing an [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) value representing the exception onto the stack. + +Each `catch` clause that branches to an outer `block` must produce values matching that `block`'s result type when a thrown exception is caught. + +### Blocktype parameters + +The optional blocktype parameters will be passed into the `try_table` block and provided as a result value after the block has run. The value can be specified before the `try_table` block, or inside. For example: + +```wat +;; Push an i32 +i32.const 42 + +;; pops an i32 as the param +try_table (param i32) + ;; The single i32 const 42 is still on the stack +end +``` + +Or: + +```wat +try_table (result i32) + ;; Push an i32 + i32.const 42 + + ;; The end of the block pops the results +end + +;; The result i32 is now available to be used here +``` + +Or you can use any combination of these structures. + +## Examples + +### Handling multiple exceptions + +This example shows how to handle multiple exceptions in a single `try_table` structure. + +#### JavaScript + +In our script, we start by grabbing a reference to a {{htmlelement("p")}} element that we will output results to. We then define two different error tags to represent a type error and a range error using the [`WebAssembly.Tag()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag/Tag) constructor. + +```html hidden live-sample___multiple-exceptions +
+``` + +```js live-sample___multiple-exceptions +const output = document.querySelector("p"); + +const typeErrorTag = new WebAssembly.Tag({ parameters: ["i32"] }); +const rangeErrorTag = new WebAssembly.Tag({ parameters: ["i32", "i32"] }); +``` + +Next, we compile and instantiate our Wasm module using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/instantiateStreaming_static) method, importing the two error tags and a function to log results to the `` element.
+
+We invoke the exported Wasm `try_multiple()` function available on the WebAssembly [`Instance`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Instance) [`exports`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Instance/exports) object multiple times, passing it two different parameters to throw different exceptions, and then finally one value that doesn't throw an exception.
+
+```js live-sample___multiple-exceptions
+async function init() {
+ const { instance } = await WebAssembly.instantiateStreaming(
+ fetch("{%wasm-url%}"),
+ {
+ env: {
+ type_error: typeErrorTag,
+ range_error: rangeErrorTag,
+ log: (code) => {
+ output.textContent += `Error code: ${code} | `;
+ },
+ },
+ },
+ );
+
+ instance.exports.try_multiple(-1); // Throws type_error, logs 10
+ instance.exports.try_multiple(101); // Throws range_error, logs 99
+ instance.exports.try_multiple(50); // Doesn't throw
+}
+
+init();
+```
+
+#### Wasm
+
+In our Wasm module, we first import our two error tags and log function. We then create a function called `$try_multiple` that has two nested `block`s to handle `$type_error`s and `$range_error`s, respectively. In the middle of the `block`s is a `try_table` structure containing two `catch` clauses, one to catch each type of error. We then call the `$might_throw` function defined later on to see whether it throws any exceptions:
+
+- If a `$type_error` is thrown, we branch to the `$on_type_error` `block` and log the payload value.
+- If a `$range_error` is thrown, we branch to the `$on_range_error` `block`, drop the first of the two payload values and log the second one, then return out of the `block`.
+- If no exception is thrown, we just return out of the `block`.
+
+The `$might_throw` function itself takes a single parameter, and checks its value. If the value is less than `0`, it throws a `$type_error` with error code `10`. If the value is greater than `100`, it throws a `$range_error` with code `99`.
+
+```wat live-sample___multiple-exceptions
+(module
+ (tag $type_error (import "env" "type_error") (param i32))
+ (tag $range_error (import "env" "range_error") (param i32 i32)) ;; carries two values
+ (import "env" "log" (func $log (param i32)))
+
+ (func $try_multiple (param $value i32)
+ (block $on_type_error (result i32)
+ (block $on_range_error (result i32 i32)
+ (try_table
+ (catch $type_error $on_type_error)
+ (catch $range_error $on_range_error)
+ (call $might_throw (local.get $value))
+ )
+ (return) ;; no exception thrown
+ )
+ ;; $range_error was caught — stack has i32 i32
+ (drop) ;; drop second payload value
+ (call $log) ;; log first payload value
+ (return)
+ )
+ ;; $type_error was caught — stack has i32
+ (call $log) ;; log the payload
+ )
+
+ (func $might_throw (param $value i32)
+ (local.get $value)
+ (i32.const 0)
+ (i32.lt_s)
+ (if
+ (then
+ (i32.const 10)
+ (throw $type_error)
+ )
+ )
+ (local.get $value)
+ (i32.const 100)
+ (i32.gt_s)
+ (if
+ (then
+ (i32.const 99)
+ (i32.const 100)
+ (throw $range_error)
+ )
+ )
+ )
+
+ (export "try_multiple" (func $try_multiple))
+)
+```
+
+#### Result
+
+{{embedlivesample("multiple-exceptions", "100%", 100)}}
+
+We call the `try_multiple()` function three times. The first time throws a `$type_error`, so error code `10` is logged. The second throws a `$range_error`, so error code `99` is logged. The third does not throw an exception.
+
+## See also
+
+- [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction
+- [`throw_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw_ref) instruction
+ - [`catch`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch) clause
+ - [`catch_all`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all) clause
+ - [`catch_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_ref) clause
+ - [`catch_all_ref`](/en-US/docs/WebAssembly/Reference/Exception_handling/try_table/catch_all_ref) clause
+- [`exnref`](/en-US/docs/WebAssembly/Reference/Value_types/exnref) type
+- [`tag`](/en-US/docs/WebAssembly/Reference/Definitions/tag) definition
diff --git a/files/en-us/webassembly/reference/javascript_interface/exception/exception/index.md b/files/en-us/webassembly/reference/javascript_interface/exception/exception/index.md
index 699993c69ab3d14..7fcfbabc5e738e9 100644
--- a/files/en-us/webassembly/reference/javascript_interface/exception/exception/index.md
+++ b/files/en-us/webassembly/reference/javascript_interface/exception/exception/index.md
@@ -6,13 +6,7 @@ browser-compat: webassembly.api.Exception.Exception
sidebar: webassemblysidebar
---
-The **`WebAssembly.Exception()`** constructor is used to create a new [`WebAssembly.Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception).
-
-The constructor accepts a [`Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) argument and a `payload` array of data fields.
-The data types of each of the payload elements must match the corresponding data type specified in the `Tag`.
-
-The constructor may also take an `options` object.
-The `options.traceStack` property can be set `true` (by default it is `false`) to indicate that a Wasm stack trace may be attached to the exception's [`stack`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/stack) property.
+The **`WebAssembly.Exception()`** constructor is used to create a new [`WebAssembly.Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) object instance.
## Syntax
@@ -24,7 +18,7 @@ new Exception(tag, payload, options)
### Parameters
- `tag`
- - : A [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) defining the data types expected for each of the values in the `payload`.
+ - : A [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) instance defining the data types expected for each of the values in the `payload`.
- `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`.
@@ -33,16 +27,48 @@ new Exception(tag, payload, options)
- : An object with the following optional fields:
- `traceStack` {{optional_inline}} {{non-standard_inline}}
- : `true` if the `Exception` may have a stack trace attached to its [`stack`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/stack) property, otherwise `false`.
- This is `false` by default (if `options` or `options.traceStack` are not provided).
+ Defaults to `false`.
### Exceptions
- `TypeError`
- : The `payload` and `tag` sequences do not have the same number of elements and/or the elements are not of matching types.
+## Description
+
+The [`Exception()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/Exception) constructor accepts a [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/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()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/getArg)).
+
## Examples
-This example shows the creation of an exception using a simple tag.
+### 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:
+
+```js
+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`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction reference page.
+
+### Manual usage
+
+This example shows manual creation of an `WebAssembly.Exception` instance.
```js
// Create tag and use it to create an exception
@@ -50,7 +76,8 @@ const tag = new WebAssembly.Tag({ parameters: ["i32", "f32"] });
const exception = new WebAssembly.Exception(tag, [42, 42.3]);
```
-The [`stack` example](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/stack#examples) shows the creation of an exception that uses the `options` parameter.
+> [!NOTE]
+> The [`stack` example](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/stack#examples) shows the creation of an exception that uses the `options` parameter.
## Specifications
diff --git a/files/en-us/webassembly/reference/javascript_interface/exception/getarg/index.md b/files/en-us/webassembly/reference/javascript_interface/exception/getarg/index.md
index f1af1cc032cbb48..fb79c94faab8800 100644
--- a/files/en-us/webassembly/reference/javascript_interface/exception/getarg/index.md
+++ b/files/en-us/webassembly/reference/javascript_interface/exception/getarg/index.md
@@ -6,14 +6,7 @@ browser-compat: webassembly.api.Exception.getArg
sidebar: webassemblysidebar
---
-The **`getArg()`** prototype method of the [`Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) object can be used to get the value of a specified item in the exception's data arguments.
-
-The method passes a [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) and will only succeed if the thrown `Exception` was created using the same tag, otherwise it will throw a `TypeError`.
-This ensures that the exception can only be read if the calling code has access to the tag.
-Tags that are neither imported into or exported from the WebAssembly code are internal, and their associated [`WebAssembly.Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) cannot be queried using this method!
-
-> [!NOTE]
-> It is not enough that the tag has an identical sequence of data types — it must have the same _identity_ (be the same tag) as was used to create the exception.
+The **`getArg()`** method of the [`Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) object can be used to get the value of a specified item in the exception's data arguments.
## Syntax
@@ -26,7 +19,7 @@ getArg(exceptionTag, index)
- `exceptionTag`
- : A [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) that must match the tag associated with this exception.
- `index`
- - : The index of the value in the data arguments to return, 0-indexed.
+ - : The index of the value in the data arguments to return.
### Return value
@@ -39,14 +32,20 @@ The value of the argument at `index`.
- {{jsxref("RangeError")}}
- : The value of the `index` parameter is greater than or equal to the number of fields in the data.
-## Examples
+## Description
-In order to get the values of an exception, the tag must be "known" to the calling code;
-it may be either imported into or exported from the calling code.
+The `getArg()` method accepts a [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) as a parameter and will only succeed if the thrown `Exception` was created using the same tag, otherwise it will throw a `TypeError`.
+This ensures that the exception can only be read if the calling code has access to the tag.
+Tags that are neither imported into or exported from the WebAssembly code are internal, and their associated exceptions cannot be queried using this method.
+
+> [!NOTE]
+> It is not enough that the tag has an identical sequence of data types — it must have the same _identity_ (be the same tag) as was used to create the exception.
+
+## Examples
-### Getting exception value from imported tag
+### Getting exception values from an imported tag
-Consider the following WebAssembly code, which is assumed to be compiled to a file "example.wasm".
+Consider the following WebAssembly code, which is assumed to be compiled to a file called `example.wasm`.
This imports a tag, which it refers to internally as `$tagname`, and exports a method `run` that can be called by external code to throw an exception using the tag.
```wat
@@ -68,7 +67,7 @@ This imports a tag, which it refers to internally as `$tagname`, and exports a m
)
```
-The code below calls [`WebAssembly.instantiateStreaming`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/instantiateStreaming_static) to import the "example.wasm" file, passing in an "import object" (`importObject`) that includes a new [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) named `tagToImport`.
+The code below calls [`WebAssembly.instantiateStreaming`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/instantiateStreaming_static) to import the `example.wasm` file, passing in an import object (`importObject`) that includes a new [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag) named `tagToImport`.
The import object defines an object with properties that match the `import` statement in the WebAssembly code.
Once the file is instantiated, the code calls the exported WebAssembly `run()` method, which will immediately throw an exception.
@@ -99,9 +98,9 @@ example.js:41 getArg 0 : 1
```
The code catches the exception and uses `getArg()` to print the value at the first index.
-In this case, it is just "1".
+In this case, the value is `1`.
-### Getting exception value from an exported tag
+### Getting exception values from an exported tag
The process for using an exported tag is very similar to that shown in the previous section.
Here is the same WebAssembly module, simply replacing the import with an export.
@@ -123,8 +122,8 @@ Here is the same WebAssembly module, simply replacing the import with an export.
)
```
-The JavaScript is similar too. In this case, we have no imports, but instead we get the exported tag and use that to get the argument.
-To make it a little more "safe", here we also test that we have the right tag using the [`is()` method](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/is).
+The JavaScript is similar too. In this case, we have no imports; instead, we get the exported tag and use that to get the argument.
+We also test that we have the right tag using the [`is()` method](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/is).
```js
let tagExportedFromWasm;
diff --git a/files/en-us/webassembly/reference/javascript_interface/exception/index.md b/files/en-us/webassembly/reference/javascript_interface/exception/index.md
index 5cdd8a7d8d69c68..3dadbb8cb343a83 100644
--- a/files/en-us/webassembly/reference/javascript_interface/exception/index.md
+++ b/files/en-us/webassembly/reference/javascript_interface/exception/index.md
@@ -8,24 +8,12 @@ sidebar: webassemblysidebar
{{AvailableInWorkers}}
-The **`WebAssembly.Exception`** object represents a runtime exception thrown from WebAssembly to JavaScript, or thrown from JavaScript to a WebAssembly exception handler.
-
-The [constructor](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/Exception) accepts a [`WebAssembly.Tag`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/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.
-Methods are provided to test whether an exception matches a particular tag, and also to get a particular value by index (if the exception matches specified tag).
-
-JavaScript and other client code can only access WebAssembly exception values, and vice versa, when the associated tag is shared (you can't just use another tag that happens to define the same data types).
-Without the matching tag, exceptions can be caught and re-thrown, but they can't be inspected.
-
-In order to make exception-throwing faster, exceptions thrown from WebAssembly generally do not include a stack trace.
-WebAssembly code that needs to provide a stack trace must call a JavaScript function to create the exception, passing `options.traceStack=true` parameter in the constructor.
-The constructor may then return an exception with a stack trace attached to the [`stack`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/stack) property.
+The **`WebAssembly.Exception`** object represents a runtime exception thrown in a Wasm module.
## Constructor
- [`WebAssembly.Exception()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/Exception)
- - : Creates a new `WebAssembly.Exception` object.
+ - : Creates a new `WebAssembly.Exception` object instance.
## Instance methods
@@ -38,7 +26,56 @@ The constructor may then return an exception with a stack trace attached to the
## Instance properties
- [`Exception.prototype.stack`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/stack) {{non-standard_inline}}
- - : Returns the stack trace for the exception, or `undefined`.
+ - : Returns the stack trace for the exception.
+
+## Description
+
+When handling Wasm exceptions from the JavaScript host, caught exceptions will have a `WebAssembly.Exception` object type.
+
+For example, you could start by constructing an error tag type using the [`WebAssembly.Tag()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Tag/Tag) constructor, like this:
+
+```js
+const myErrorTag = new WebAssembly.Tag({ parameters: ["i32"] });
+```
+
+You can then import it into a Wasm module like this:
+
+```js
+const env = {
+ my_error: myErrorTag,
+};
+
+WebAssembly.instantiateStreaming(fetch("module.wasm"), { env }).then( ... )
+```
+
+You could then try running an exported Wasm function in a [`try...catch`](/en-US/docs/Web/JavaScript/Reference/Statements/try...catch) statement. If the function throws, the error propagated to the `catch` block will be a [`WebAssembly.Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) object instance.
+
+```js
+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
+ }
+ }
+ },
+);
+```
+
+You can check whether it has the same exception type we defined earlier (`myErrorTag`) using [`Exception.prototype.is()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/is), and then access the exception's payload using [`Exception.prototype.getArg()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/getArg)).
+
+JavaScript and other client code can only access WebAssembly exception values, and vice versa, when the associated tag is shared (you can't just use another tag that happens to define the same data types).
+Without the matching tag, exceptions can be caught and re-thrown, but they can't be inspected.
+
+In order to make exception-throwing faster, exceptions thrown from WebAssembly generally do not include a stack trace.
+WebAssembly code that needs to provide a stack trace must call a JavaScript function to create the exception, passing `options.traceStack=true` parameter in the constructor.
+The constructor may then return an exception with a stack trace attached to the [`stack`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/stack) property.
## Examples
diff --git a/files/en-us/webassembly/reference/javascript_interface/exception/is/index.md b/files/en-us/webassembly/reference/javascript_interface/exception/is/index.md
index ce0b3d6488b42da..2203a0f092588c3 100644
--- a/files/en-us/webassembly/reference/javascript_interface/exception/is/index.md
+++ b/files/en-us/webassembly/reference/javascript_interface/exception/is/index.md
@@ -6,13 +6,10 @@ browser-compat: webassembly.api.Exception.is
sidebar: webassemblysidebar
---
-The **`is()`** prototype method of the [`Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) object can be used to test if the `Exception` matches a given tag.
+The **`is()`** method of the [`Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) object can be used to test if the `Exception` matches a given tag.
The method might be used to test that a tag is correct before passing it to [`Exception.prototype.getArg()`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/getArg) to get the passed values.
-It can be used on tags created in JavaScript or created in WebAssembly code and exported to JavaScript.
-
-> [!NOTE]
-> It is not enough that the tag has an identical sequence of data types — it must have the same _identity_ (be the same tag) as was used to create the exception.
+It can be used on tags created in JavaScript and those created in WebAssembly code and exported to JavaScript.
## Syntax
@@ -27,7 +24,9 @@ is(tag)
### Return value
-A boolean `true` if the specified tag matches the exception, and `false` otherwise.
+A boolean value — `true` if the specified tag matches the exception, and `false` otherwise.
+
+To return `true`, it is not enough for the tag to have an identical sequence of data types — it must have the same _identity_ (be the same tag) as was used to create the exception.
## Examples
@@ -40,22 +39,22 @@ const exception1 = new WebAssembly.Exception(tag1, [42, 42.3]);
// Verify that "tag1" matches this exception
console.log(`Tag1: ${exception1.is(tag1)}`);
-
-// Log output:
-// Tag1: true
```
+This will log `Tag1: true` to the console.
+
We can also demonstrate that this exception will not match another tag even if the tag is created with the same parameters.
```js
// Create a new tag (with same parameters) and verify it does not match the exception
const tag2 = new WebAssembly.Tag({ parameters: ["i32", "f64"] });
console.log(`Tag2: ${exception1.is(tag2)}`);
-
-// Log output:
-// Tag2: false
```
+This will log `Tag2: false` to the console.
+
+For a full working example, see the [`throw`](/en-US/docs/WebAssembly/Reference/Exception_handling/throw) instruction reference page.
+
## Specifications
{{Specifications}}
diff --git a/files/en-us/webassembly/reference/javascript_interface/exception/stack/index.md b/files/en-us/webassembly/reference/javascript_interface/exception/stack/index.md
index 265758beb8c4865..110e8fb1f305a85 100644
--- a/files/en-us/webassembly/reference/javascript_interface/exception/stack/index.md
+++ b/files/en-us/webassembly/reference/javascript_interface/exception/stack/index.md
@@ -10,36 +10,38 @@ sidebar: webassemblysidebar
{{non-standard_header}}
-The read-only **`stack`** property of an object instance of type [`WebAssembly.Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) _may_ contain a stack trace.
-
-Exceptions from WebAssembly code do not include a stack trace by default.
-
-If WebAssembly code needs to provide a stack trace, it must call a JavaScript function to create the exception, passing `options.traceStack=true` parameter in the [constructor](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/Exception).
-The virtual machine can then attach a stack trace to the exception object returned by the constructor.
-
-> [!NOTE]
-> Stack traces are not normally sent from WebAssembly code to improve performance.
-> The ability to add stack traces to these exceptions is provided for developer tooling, and is not generally recommended for broader use.
+The **`stack`** read-only property of the [`WebAssembly.Exception`](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception) object _may_ contain a stack trace.
## Value
A string containing the stack trace, or {{jsxref("undefined")}} if no trace has been assigned.
The stack trace string lists the locations of each operation on the stack in WebAssembly format.
-This is a human-readable string indicating the URL, name of the function type called, the function index, and its offset in the module binary.
+This is a human-readable string indicating the URL, name of the function type called, function index, and its offset in the module binary.
It has approximately this format (see [stack trace conventions](https://webassembly.github.io/spec/web-api/index.html#conventions) in the specification for more information):
```plain
${url}:wasm-function[${funcIndex}]:${pcOffset}
```
+## Description
+
+Exceptions from WebAssembly code do not include a stack trace by default.
+
+If WebAssembly code needs to provide a stack trace, it must call a JavaScript function to create the exception, passing the `options.traceStack=true` parameter in the [constructor](/en-US/docs/WebAssembly/Reference/JavaScript_interface/Exception/Exception).
+The virtual machine can then attach a stack trace to the exception object returned by the constructor.
+
+> [!NOTE]
+> Stack traces are not normally sent from WebAssembly code to improve performance.
+> The ability to add stack traces to these exceptions is provided for developer tooling, and is not generally recommended for broader use.
+
## Examples
This example demonstrate how to throw an exception from WebAssembly that includes a stack trace.
-Consider the following WebAssembly code, which is assumed to be compiled to a file named **example.wasm**.
+Consider the following WebAssembly code, which is assumed to be compiled to a file named `example.wasm`.
This imports a tag, which it refers to as `$tagname` internally, and imports a function that it refers to as `$throwExnWithStack`.
-It exports the method `run` that can be called by external code to call `$throwExnWithStack` (and hence the JavaScript function).
+It exports the method `run` that can be called by external code to call `$throwExnWithStack`.
```wat
(module
@@ -57,10 +59,10 @@ It exports the method `run` that can be called by external code to call `$throwE
)
```
-The JavaScript code below defines a new tag `tag` and the function `throwExceptionWithStack`.
+The JavaScript code below defines a new tag `tag` and the function `throwExceptionWithStack()`.
These are passed to the WebAssembly module in the `importObject` when it is instantiated.
-Once the file is instantiated, the code calls the exported WebAssembly `run()` method, which will immediately throw an exception.
+Once the module is instantiated, the code calls the exported WebAssembly `run()` method, which will immediately throw an exception.
The stack is then logged from the `catch` statement.
```js
@@ -93,7 +95,7 @@ WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject)
// @http://WebAssembly
details: closed
@@ -127,6 +129,8 @@ sidebar:
title: v128
- link: /WebAssembly/Reference/Value_types/funcref
title: funcref
+ - link: /WebAssembly/Reference/Value_types/exnref
+ title: exnref
- link: /WebAssembly/Reference/Value_types/externref
title: externref
- link: /WebAssembly/Reference/Definitions
@@ -142,6 +146,8 @@ sidebar:
title: global
- link: /WebAssembly/Reference/Definitions/table
title: table
+ - link: /WebAssembly/Reference/Definitions/tag
+ title: tag
- title: Instructions
details: closed
children:
@@ -150,6 +156,19 @@ sidebar:
link: /WebAssembly/Reference/Control_flow
title: Control flow
details: closed
+ - link: /WebAssembly/Reference/Exception_handling
+ title: Exception handling
+ details: closed
+ children:
+ - link: /WebAssembly/Reference/Exception_handling/throw
+ title: throw
+ - link: /WebAssembly/Reference/Exception_handling/throw_ref
+ title: throw_ref
+ - type: listSubPages
+ path: /WebAssembly/Reference/Exception_handling/try_table
+ link: /WebAssembly/Reference/Exception_handling/try_table
+ title: try_table
+ details: closed
- type: listSubPages
path: /WebAssembly/Reference/Memory
link: /WebAssembly/Reference/Memory
diff --git a/front-matter-config.json b/front-matter-config.json
index 1a5830725b06d5e..f696fa8817f7922 100644
--- a/front-matter-config.json
+++ b/front-matter-config.json
@@ -354,6 +354,7 @@
"webassembly-instance-property",
"webassembly-instance-method",
"webassembly-static-method",
+ "webassembly-static-property",
"webassembly-instruction"
]
}
From db5b185b67e592d5d2c95b8c32c1f8f3f90a5117 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Fri, 22 May 2026 22:16:20 +0200
Subject: [PATCH 3/3] ci(deps-dev): bump @mdn/fred from 2.6.2 to 2.6.4 (#44228)
Bumps [@mdn/fred](https://github.com/mdn/fred) from 2.6.2 to 2.6.4.
- [Release notes](https://github.com/mdn/fred/releases)
- [Changelog](https://github.com/mdn/fred/blob/main/CHANGELOG.md)
- [Commits](https://github.com/mdn/fred/compare/v2.6.2...v2.6.4)
---
updated-dependencies:
- dependency-name: "@mdn/fred"
dependency-version: 2.6.4
dependency-type: direct:development
update-type: version-update:semver-patch
...
Signed-off-by: dependabot[bot]