Notes

Throwing errors in JavaScript

Edit on GitHub

JavaScript
2 minutes
  • Throwing stops execution
  • Put the throw inside a try .. catch block
  • Once execution stops, the control will be passed to the first catch block it finds. If no catch then the program will terminate
  • You can re-throw errors
  • You can throw different types of errors
1// throw Examples
2throw 'Error2'; // generates an exception with a string value
3throw 42;       // generates an exception with the value 42
4throw true;     // generates an exception with the value true
5throw new Error('Required');  // generates an error object with the message of Required
1// Errors and Exceptions
2console.log(e) // ReferenceError: blah is not defined
3console.log(e.stack) // tells you line number, not supported by some
4console.log(e.name) // ReferenceError
5console.log(e.message) // blah is not defined

Example

 1/*
 2 * Complete the isPositive function.
 3 * If 'a' is positive, return "YES".
 4 * If 'a' is 0, throw an Error with the message "Zero Error"
 5 * If 'a' is negative, throw an Error with the message "Negative Error"
 6 */
 7function isPositive(a) {
 8    // if (a === 0) { throw 'Zero Error'}
 9    // if (a < 0) { throw 'Negative Error'}
10    // return 'YES'
11
12    if (a >= 1) {
13        return 'YES'
14    } else if (a === 0) {
15        // put throw inside a try/catch so the execution doesn't stop
16        try {
17            throw new Error('Zero Error')
18        } catch (e) {
19            // e will be whatever error/exception we throwed earlier
20            return e.message // 'Zero Error'
21        }
22    } else {
23        try {
24            throw new Error('Negative Error')
25        } catch (error) {
26            return error.message
27        }
28    }
29}