javascript Exception handling statements(异常处理)

使用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

发布了1794 篇原创文章 · 获赞 582 · 访问量 154万+

猜你喜欢

转载自blog.csdn.net/claroja/article/details/104310836
今日推荐