javascript Exception handling statements(异常处理)

本文深入讲解JavaScript中的错误处理机制,包括如何使用throw语句抛出异常,try...catch语句捕获并处理异常,以及finally语句确保资源的正确关闭。文章详细介绍了不同类型的异常,如字符串、数字、布尔值和对象类型,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用throw抛出exceptions,使用try..catch来处理

throw

thow来抛出

throw 'Error2';   // String type
throw 42;         // Number type
throw true;       // Boolean type
throw {toString: function() { return "I'm an object!"; } };

try…catch statement

If an exception is thrown, the try…catch statement catches it.

catch (catchID) {
  statements
}
try {
  throw 'myException'; // generates an exception
}
catch (err) {
  // statements to handle any exceptions
  logMyErrors(err);    // pass exception object to error handler
}

finally

openMyFile();
try {
  writeMyFile(theData); // This may throw an error
} catch(e) {  
  handleError(e); // If an error occurred, handle it
} finally {
  closeMyFile(); // Always close the resource
}

参考:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Error_types
https://developer.mozilla.org/en-US/docs/Web/API/DOMException
https://developer.mozilla.org/en-US/docs/Web/API/DOMError

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值