Javascript Reference
Categories: Operators

javascript Operators try/catch

@July 23, 2008, 5:23 p.m.
try/catch Firefox/Netscape/NN 6 IE 5 ECMA 3  

This construction provides a nondisruptive way to trap for errors (exceptions) and handle them gracefully. Both parts of this exception-handling construction are required. If an error occurs in the try portion, execution immediately branches to the catch portion, where your scripts can display alert dialogs, modify data, or any other task that keeps the JavaScript interpreter from triggering a disruptive error message. Exceptions that occur naturally (i.e., they are not thrown by a throw statement) pass an instance of the Error object as a parameter to the catch section. Statements inside the catch section can examine properties of the error object to determine how to handle exceptions that land there. Thus, one catch portion can handle errors of various types.


You can use try/catch constructions only in browsers that support them. To protect older browsers from seeing this construction, place all affected code inside a <script> tag that explicitly requires JavaScript 1.5 or later (with the language = "JavaScript1.5" attribute.

function insertOneNode(baseNode, newNode, position) {
  try {
    baseNode.insertBefore(newNode, baseNode.childNodes[position]);
  catch (e) {
    // handle W3C DOM Exception types
    switch ( {
        // process bad tree hierarchy reference
      case "NOT_FOUND_ERR" :
        // process bad refNode reference
      default :
        // process all other exceptions
  return true;

Powered by Linode.