0%

javascript-try-catch-finally

Introduction

try

catch

JavaScript中的catch不能按类型捕获异常,只能捕获所有异常。如果需要按类型捕获异常,可以使用if语句判断异常类型。

1
2
3
4
5
6
7
8
9
10
11
12
13
try {
myFunction();
} catch (e) {
if (e instanceof ReferenceError) {
console.error(`ReferenceError:${e.message}`);
} else if (e instanceof TypeError) {
console.error(`TypeError: ${e.message}`);
} else if (e instanceof SyntaxError) {
console.error(`SyntaxError: ${e.message}`);
} else if (e instanceof Error) {
console.error(`Error: ${e.message}`);
}
}

Java等其他类型的语言不同,JS不能像下面这样捕获异常。JS中一个try只能对应一个catch

1
2
3
4
5
6
7
8
9
10
11
try {
myFunction();
} catch (ReferenceError) {
console.error(`ReferenceError:${e.message}`);
} catch (TypeError) {
console.error(`TypeError: ${e.message}`);
} catch (SyntaxError) {
console.error(`SyntaxError: ${e.message}`);
} catch (Error) {
console.error(`Error: ${e.message}`);
}

finally

returnfinally同时存在时,finally会在return之前执行。

1
2
3
4
5
6
7
function test() {
try {
return 1;
} finally {
console.log('finally');
}
}