Throwing

Throwing is a shift of control from the current statement to the nearest containing try...catch statement on the call stack. If no such try...catch statement exists, then the execution of the program will terminate entirely. Throwing is conventionally used to raise exceptions when specific requirements or expectations are not met:

function nameToUpperCase(name) {
if (typeof name !== 'string') {
throw new TypeError('Name should be a string');
}
return name.toUpperCase();
}

To catch this error, we would need to have a try...catch block somewhere on the call-stack, wrapping the call to the nameToUpperCase function or the call to the function that calls it (and so on):

let theUpperCaseName;
try {
theUpperCaseName = nameToUpperCase(null);
} catch(e) {
e.message; // => "Name should be a string"
}

It is a best practice to throw objects that are instances of the natively provided generic Error constructor. There are several native sub-classed constructors of Error:

  • SyntaxError: This indicates that a parsing error has occurred
  • TypeError: This indicates an unsuccessful operation when none of the other Error objects are appropriate
  • ReferenceError: This indicates that an invalid reference value has been detected
  • RangeError: This indicates a value that is not in the set or range of allowable values
  • URIError: This indicates that a URI handling function was used in a way that is incompatible with its definition

JavaScript will naturally raise such exceptions to you if you misuse native APIs or produce invalid syntax, but you can also use these constructors yourself to provide more semantically meaningful errors to your fellow programmers. If none of the preceding are suitable, then you can directly use Error or extend from it to produce your own specialized instance, as follows:

class NetworkError extends Error {}

async function makeDataRequest() {
try {
const response = await fetch('/data');
} catch(e) {
throw NetworkError('Cannot fetch data');
}
// ... (process response) ...
}

All Error instances will contain a name and message property. Depending on the JavaScript implementation, there may also be additional properties related to the stack trace of the error. In both the V8 JavaScript engine (used in Chromium and Node.js) and in SpiderMonkey (Mozilla), there is a stack property that gives us serialized call stack information:

try {
throw new Error;
} catch(e) {
e.stack; // => "Error at filename.js:2:9"
}

There may be unique situations where you wish to throw a value that is not an Error instance, and technically, this is perfectly legal, but it is rarely useful to do so. It's best to only throw in the case of an actual error, and in that case, it is best to use an appropriate Error object to represent the error. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.198.49