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