错误

To the book page

Retry

大概率触发MultiplicatorUnitFailure错误,承接直到运行成功并返回结果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class MultiplicatorUnitFailure extends Error {}

function primitiveMultiply(a, b) {
if (Math.random() < 0.2) {
return a * b;
} else {
throw new MultiplicatorUnitFailure("Klunk");
}
}

function reliableMultiply(a, b) {
// Your code here.
for(;;){
try{
var ans = primitiveMultiply(a,b);
break;
}catch(e){
if(e instanceof MultiplicatorUnitFailure){
console.log(e);
}else {
throw e;
}
}
}
return ans;
}

console.log(reliableMultiply(8, 8));
// → 64

The locked box

先开锁,不管之后干什么都要在函数执行完毕返回前锁上盒子,因为中间操作可能抛出异常导致后面函数不执行,用finally执行关闭函数即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const box = new class {
locked = true;
#content = [];

unlock() { this.locked = false; }
lock() { this.locked = true; }
get content() {
if (this.locked) throw new Error("Locked!");
return this.#content;
}
};

function withBoxUnlocked(body) {
// Your code here.
box.unlock();
try{
body();
}catch(e){
throw e;
}finally{
box.lock();
}
}

withBoxUnlocked(() => {
box.content.push("gold piece");
});

try {
withBoxUnlocked(() => {
throw new Error("Pirates on the horizon! Abort!");
});
} catch (e) {
console.log("Error raised: " + e);
}
console.log(box.locked);
// → true