TL ; DR:
When a method can't do what it was asked, it throws an error. The code that called it catches the error with try and catch.
spend(amount: number): void {
if (amount > this.money) {
throw new Error("not enough money");
}
this.money -= amount;
}
try {
wallet.spend(80);
} catch (e) {
console.log("error: " + (e as Error).message);
}
Full lesson:
Some requests can't be done. A wallet with 50 can't spend 80.
The method could return a special value, like -1. But the caller may forget to check it. Then the program goes on with a wrong number.
An exception is better. It is an error that the program can't miss.
Throwing an error
throw new Error("not enough money")stops the method at once.- The lines after it don't run. So the wallet keeps its money.
Erroris the built-in error type.- The text in the parentheses is the error's message.
Catching it
- Put the call inside a
tryblock. - When the call throws, the rest of the
tryblock is skipped. - The
catch (e)block runs instead.eis what was thrown. - Any value can be thrown, so TypeScript doesn't know the type of
e. e as Errortells it thateis anError. Then.messageis its message.- After the
catchblock, the program goes on as usual.
An error that nobody catches stops the whole program. Node prints the error and the line where it happened.
Your task
A Wallet starts with 50. Its spend method takes money out and returns what is left.
- In
spend, throw anErrorwhenamountis more thanthis.money. Its message is"not enough money". - In the loop, call
spendinside atryblock. Log what was spent and what is left. - Catch the error. Log
error:and its message.
The loop tries to spend 20, then 40, then 30.
Expected output:
spent 20, 30 left
error: not enough money
spent 30, 0 leftFree plan: 30 tutor messages. Premium is unlimited.
