- The try statement lets you test a block of code for errors.
- The catch statement lets you handle the error.
- The throw statement lets you create custom errors.
- The finally statement lets you execute code, after try and catch, regardless of the result.
Use a tool such as JSHint or JSLint to help you find implicit exceptions like reference errors on undefined variables.
Here is an example of using try-catch to handle a potential process-crashing exception. This code try to parse a string into json object.
var jsonStr = 'your json object in string';
However, try-catch works only for synchronous code. Because the Node platform is primarily asynchronous (particularly in a production environment), try-catch won’t catch a lot of exceptions.
The error object provides two useful properties: name and message.
- name: Sets or returns an error name
- message: Sets or returns an error message (a string)
Six different values can be returned by the error name property
- EvalError: An error has occurred in the eval() function
- RangeError: A number “out of range” has occurred
- ReferenceError: An illegal reference has occurred
- SyntaxError: A syntax error has occurred
- TypeError: A type error has occurred
- URIError: An error in encodeURI() has occurred