at repl:1:1 // <-- For now feel free to ignore anything below this point, these are Node's internals
at realRunInThisContextScript (vm.js:22:35)
at sigintHandlersWrap (vm.js:98:12)
at ContextifyScript.Script.runInThisContext (vm.js:24:12)
at REPLServer.defaultEval (repl.js:313:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.onLine (repl.js:513:10)
总结:调用方法,方法便会添加到堆栈顶部,执行完毕之后,它就会从堆栈中弹出。
Error对象 和 Error处理
当程序发生错误时,通常都会抛出一个Error对象。Error对象也可以作为一个原型,用户可以扩展它并创建自定义错误。
Error.prototype对象通常有以下属性:
constructor- 实例原型的构造函数。
message - 错误信息
name - 错误名称
以上都是标准属性,(但)有时候每个环境都有其特定的属性,在例如Node,Firefox,Chorme,Edge,IE 10+,Opera 和 Safari 6+ 中,还有一个包含错误堆栈记录的stack属性。错误堆栈记录包含从(堆栈底部)它自己的构造函数到(堆栈顶部)所有的堆栈帧。
如果想了解更多关于Error对象的具体属性,我强烈推荐MDN上的这篇文章。
抛出错误必须使用throw关键字,你必须将可能抛出错误的代码包裹在try代码块内并紧跟着一个catch代码块来捕获抛出的错误。
正如Java中的错误处理,try/catch代码块后紧跟着一个finally代码块在JavaScript中也是同样允许的,无论try代码块内是否抛出异常,finally代码块内的代码都会执行。在完成处理之后,最佳实践是在finally代码块中做一些清理的事情,(因为)无论你的操作是否生效,都不会影响到它的执行。
(鉴于)上面所谈到的所有事情对大多数人来讲都是小菜一碟,那么就让我们来谈一些不为人所知的细节。
try代码块后面不必紧跟着catch,但(此种情况下)其后必须紧跟着finally。这意味着我们可以使用三种不同形式的try语句:
try...catch
try...finally
try...catch...finally
Try语句可以像下面这样互相嵌套:
try {
try {
throw new Error('Nested error.'); // The error thrown here will be caught by its own `catch` clause
} catch (nestedErr) {
console.log('Nested catch'); // This runs
}
} catch (err) {
console.log('This will not run.');
}
你甚至还可以在catch和finally代码块中嵌套try语句:
try {
throw new Error('First error');
} catch (err) {
console.log('First catch running');
try {
throw new Error('Second error');
} catch (nestedErr) {
console.log('Second catch running.');
}
}
try {
console.log('The try block is running...');
} finally {
try {
throw new Error('Error inside finally.');
} catch (err) {
console.log('Caught an error inside the finally block.');
}
}
(责任编辑:admin)