JavaScript Try Catch:异常处理说明

The try...catch..finally statement specifies a block of code to try along with a response should an error occur. The try statement contains one or more try blocks, and ends with at least one catch and/or a finally clause.

try...catch..finally语句指定代码块,以在发生错误时尝试与响应一起使用。 try语句包含一个或多个try块,并以至少一个catch和/或finally子句结尾。

try...catch(try...catch:)

try {
   throw new Error('my error');
} catch (err) {
  console.error(err.message);
}

// Output: my error

try...finally(try...finally:)

try {
   throw new Error('my error');
} finally {
  console.error('finally');
}

// Output: finally

When you don't use a catch statement, the error is not "caught", even though the code in the finally block is executed. Instead, the error will continue to the upper try block (or main block).

当您不使用catch语句时,即使执行了finally块中的代码,也不会“捕获”该错误。 而是,错误将继续到上部try块(或主块)。

try...catch...finally(try...catch...finally:)

try {
   throw new Error('my error');
} catch (err) {
  console.error(err.message);
} finally {
  console.error('finally');
}

// Output:
// my error
// finally

Typical usage:

典型用法:

try {
   openFile(file);
   readFile(file)
} catch (err) {
  console.error(err.message);
} finally {
  closeFile(file);
}

嵌套try...catch(Nested try...catch:)

You can also:

你也可以:

  • Nest a try-catch statement inside a try block.

    try-catch语句嵌套在try块内。

You can nest a try...catch statement within a try block. For example, to throw an error upwards:

您可以在try块中嵌套try...catch语句。 例如,向上抛出错误:

try {
  try {
    throw new Error('my error');
  } catch (err) {
    console.error('inner', err.message);
    throw err;
  } finally {
    console.log('inner finally');
  }
} catch (err) {
  console.error('outer', err.message);
}

// Output: 
// inner my error 
// inner finally 
// outer my error

翻译自: https://www.freecodecamp.org/news/error-handling-and-try-catch-throw/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值