- 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测试参数类型
- 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 atrystatement. 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 thecatchclause:
try { // Do work . . . } catch (e) { // Handle exceptions . . . }
The variable in thecatchclause (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:nameandmessage. 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 theagekey is not enclosed in double quotes.)
The name of an object produced with theErrorfunction 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 thestack 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 thecatchclause is entered, the exception is deemed to be handled. Processing resumes normally, executing the statements in thecatchclause. Thecatchclause can exit with areturnorbreakstatement, or it can be completed by executing its last statement. In that case, execution moves to the next statement after thecatchclause.
If you log exceptions at one level of your code but deal with failure at a higher level, then you want torethrowthe exception after logging it:
try { // Do work . . . } catch (e) { console.log(e) throw e // Rethrow to a handler that deals with the failure }