JavaScript try catch finally 基本用

2018-04-01  本文已影响0人  novaDev

语法

try {
    // do sth
}
catch(e) {
    // solve error
}
finally {
    // do the last thing
}

规则

延长作用域链
catch语句块会产生延长作用域的作用:

var e = {message: 'this is a message'};
var s = 'this is a s';
try {
    throw new Error('error!');
} catch (e) {
    console.log(e.message); //this is a message
    var s = 'this is another s';
    var e = {message: 'this is another message'};
    console.log(e.message); //this is another message
}

console.log(s); //this is another s
console.log(e); //{message: 'this is a message'}

当js执行到catch代码块时,作用域链也被临时改变了。异常对象e被加入了一个新的作用域对象,并且优先于活动对象成为作用域链第一位。

要注意的是:catch代码块中定义的变量可以被后续的代码所访问,但是异常对象e是无法被访问的,即使使用var语句重新定义了e,这个变量仍然是处在新创建的作用域对象里,而这个作用域对象在catch代码块结束后就会立刻被销毁,因此最后一行所访问的e依然只能访问到第一行所定义的e。

上一篇 下一篇

猜你喜欢

热点阅读