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
return
和finally
同时存在时,finally
会在return
之前执行。
1 2 3 4 5 6 7
| function test() { try { return 1; } finally { console.log('finally'); } }
|