link0 link1 link2 link3 link4 link5 link6 link7 link8 link9 link10 link11 link12 link13 link14 link15 link16 link17 link18 link19 link20 link21 link22 link23 link24 link25 link26 link27 link28 link29 link30 link31 link32 link33 link34 link35 link36 link37 link38 link39 link40 link41 link42 link43 link44 link45 link46 link47 link48 link49 link50 link51 link52 link53 link54 link55 link56 link57 link58 link59 link60 link61 link62 link63 link64 link65 link66 link67 link68 link69 link70 link71 link72 link73 link74 link75 link76 link77 link78 link79 link80 link81 link82 link83 link84 link85 link86 link87 link88 link89 link90 link91 link92 link93 link94 link95 link96 link97 link98 link99 link100 link101 link102 link103 link104 link105 link106 link107 link108 link109 link110 link111 link112 link113 link114 link115 link116 link117 link118 link119 link120 link121 link122 link123 link124 link125 link126 link127 link128 link129 link130 link131 link132 link133 link134 link135 link136

Use try-catch in javascript

try/catch/throw/finally

Try-catch is a JavaScript language construct that you can use to catch exceptions in synchronous code. Use try-catch, for example, to handle JSON parsing errors as shown below.

  • 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.

1
2
3
4
5
6
7
var jsonStr = 'your json object in string';
try {
var jsonObj = JSON.parse(jsonStr);
} catch (e) {
// handle exception
console.error(e);
}

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

JavaScript has a built in error object that provides error information when an error occurs.

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