很多编程语言都有异常机制,JS在ES3开始也提供了类似的异常处理机制。要先要了解异常的原理,就得先了解JS得函数调用栈。
什么叫函数调用栈?
先看以下代码
function introduction(name){
console.log("我是"+name);
}
introduction("一个人");
console.log("呵呵");
这个代码的执行顺序是:调用introduction函数,此时控制流跳转到函数的开头(第二行),然后调用console.log函数。控制流跳转到该函数并完成操作之后返回到第二行,接着控制流执行到introduction的末尾(第三行),接着返回到调用该函数的位置(第五行),最后再次调用console.log
如下所示
top
introduction
console.log
introduction
top
console.log
top
因为程序需要在函数执行完毕后跳转回调用该函数的代码位置,因此计算机必须记住函数调用的上下文。例如上文中的第一个console.log调用结束之后要返回到introduction函数,而第二个console.log执行完毕后需要回到代码结尾的位置。
一般讲计算机存储这个上下文的区域称之为调用栈。每当函数调用时,当前的上下文信息栈顶。当函数返回时,系统会删除存储在栈顶的上下文信息,并使用该信息继续执行程序。