欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

try catch 语句

程序员文章站 2024-03-20 18:38:04
...

try代码块抛出错误(上例用的是throw语句),JavaScript 引擎就立即把代码的执行,转到catch代码块,或者说错误被catch代码块捕获了。catch接受一个参数,表示try代码块抛出的值。
如果你不确定某些代码是否会报错,就可以把它们放在try…catch代码块之中,便于进一步对错误进行处理。

function isErr() {
  try {
    throw new Error('出错了……');
    console.log('此行不会执行');
  }catch(e){
    console.log(e)
  } finally {
    console.log('我一定会执行');
  }
}

isErr()

return

function idle(x) {
  try {
    console.log(x);
    return 'result';
  } finally {
    console.log("FINALLY");
  }
}

idle('hello')
// hello
// FINALLY
// "result"
相关标签: try catch