Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.16 Catching Exceptions

queen.jpg

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
}
  • + Share This
  • 🔖 Save To Your Account