Errors
try, catch, finally and throw work as in TypeScript. throw takes a
new Error(…), a RangeError, a TypeError, a class that extends one of them, or what a
catch took (throw e). A class of error has a message, a name and fields of its
own, and e instanceof OutOfGold tells the classes apart.
class OutOfGold extends Error {
constructor(public need: number) { super(`need ${need} more`); }
}
program(() => {
let gold = 30;
function buy(cost: number) {
if (cost > gold) throw new OutOfGold(cost - gold);
gold -= cost;
}
try {
buy(20);
buy(50);
} catch (e) {
if (e instanceof OutOfGold) print(`${e.message} (${e.need})`); // need 40 more (40)
else throw e;
} finally {
print(`${gold} left`); // 10 left
}
});
- An error goes up through the functions to the nearest
catch.finallyruns however thetryis left: areturn, abreak, or an error on its way out. - An error nothing catches is shown in the game in red, with its line ("TrigScript:
uncaught OutOfGold: need 20 more, line 12."), and Simulate lists it at the
throw. The program or task stops there. A handler of an event gives up that one turn and goes on listening. - A
trymay spansleepandawait. An error in one branch ofPromise.allorPromise.raceleaves the statement, and the other branches stop where they are. - A caught error cannot be kept in a variable, an array or a field. Copy what you need out
of it in the
catch, or put it in a field of your own class. - An index past an array's end and a full pool are not errors: the game passes over them, and Simulate and the tests say where.