throw: Wasm-Ausnahmebehandlungsanweisung
Die throw-Ausnahmebehandlungsanweisung wirft eine Ausnahme eines bestimmten Typs, wie durch eine Tag- Definition festgelegt.
Probieren Sie es aus
(module
;; Import the error tag from JS
(tag $my_error (import "env" "my_error") (param i32))
(func $might_throw (param $value i32)
;; If value is negative, run the if block
(local.get $value)
(i32.const 0)
(i32.lt_s)
(if
(then
;; Push the error code onto the stack, then throw an exception
(i32.const 42) ;; error code payload
(throw $my_error) ;; throw with the tag
)
)
)
(export "might_throw" (func $might_throw))
)
// Define error tag in JS
const myErrorTag = new WebAssembly.Tag({ parameters: ["i32"] });
// Import the tag into the module
const env = {
my_error: myErrorTag,
};
WebAssembly.instantiateStreaming(fetch("{%wasm-url%}"), { env }).then(
(result) => {
try {
// Negative value causes function to throw
result.instance.exports.might_throw(-1);
} catch (e) {
if (e instanceof WebAssembly.Exception && e.is(myErrorTag)) {
// 0 is the first payload value, which is equal to 42
const errorCode = e.getArg(myErrorTag, 0);
console.log("Error code:", errorCode);
} else {
// Throw other errors
throw e;
}
}
},
);
Syntax
throw identifier
throw-
Die
throw-Anweisung. identifier-
Ein Bezeichner für den Ausnahmetag-Typ, der geworfen werden soll. Dies kann sein:
- Ein identifizierender Name, wie durch den
identifierdes entsprechenden Tag-Typs definiert. - Eine Tag-Indexnummer —
0um den ersten angegebenen Tag zu identifizieren,1für den zweiten usw.
- Ein identifizierender Name, wie durch den
Typ
[payload1, payload2, payloadN] -> []
payload-Werte-
Die
payload-Werte, die normalerweise identifizierende Fehlercodes darstellen.
Die payload-Werte können abgerufen werden, wenn die Ausnahme abgefangen wird, entweder durch Klauseln wie catch und catch_ref, oder in JavaScript über eine try...catch-Anweisung.
Siehe die tag-Definitionsreferenzseite für Beispiele von beiden.
Binärcodierung
| Anweisung | Binärformat | Beispieltext => binär |
|---|---|---|
throw |
0x08 x:tagidx |
(throw $tag (i32.const 42)) => 0x41 0x2a 0x08 0x00 |