- 3.1 Declaring Functions
- 3.2 Higher-Order Functions
- 3.3 Function Literals
- 3.4 Arrow Functions
- 3.5 Functional Array Processing
- 3.6 Closures
- 3.7 Hard Objects
- 3.8 Strict Mode
- 3.9 Testing Argument Types
- 3.10 Supplying More or Fewer Arguments
- 3.11 Default Arguments
- 3.12 Rest Parameters and the Spread Operator
- 3.13 Simulating Named Arguments with Destructuring
- 3.14 Hoisting
- 3.15 Throwing Exceptions
- 3.16 Catching Exceptions
- 3.17 The finally Clause
- Exercises
3.16 Catching Exceptions
To catch an exception, use a try statement. In Chapter 2, you saw how to catch an exception if you are not interested in the exception value. If you want to examine the exception value, add a variable to the catch clause:
try { // Do work . . . } catch (e) { // Handle exceptions . . . }
The variable in the catch clause (here, e) contains the exception value. As you saw in the preceding section, an exception value is conventionally an error object. Such an object has two properties: name and message. For example, if you call
JSON.parse('{ age: 42 }')
an exception is thrown with the name 'SyntaxError' and message 'Unexpected token a in JSON at position 2'. (The string in this example is invalid JSON because the age key is not enclosed in double quotes.)
The name of an object produced with the Error function is 'Error'. The JavaScript virtual machine throws errors with names 'SyntaxError', 'TypeError', 'RangeError', 'ReferenceError', 'URIError', or 'InternalError'.
In the handler, you can record that information in a suitable place. However, in JavaScript it is not usually productive to analyze the error object in detail, as you might in languages such as Java or C++.
When you log an error object on the console, JavaScript execution environments typically display the stack trace—the function and method calls between the throw and catch points. Unfortunately, there is no standard way of accessing the stack trace for logging it elsewhere.
When the catch clause is entered, the exception is deemed to be handled. Processing resumes normally, executing the statements in the catch clause. The catch clause can exit with a return or break statement, or it can be completed by executing its last statement. In that case, execution moves to the next statement after the catch clause.
If you log exceptions at one level of your code but deal with failure at a higher level, then you want to rethrow the exception after logging it:
try { // Do work . . . } catch (e) { console.log(e) throw e // Rethrow to a handler that deals with the failure }