Javascript - Exception

javascript
javascript-dom

http://www.sitepoint.com/proper-error-handling-javascript/
https://davidwalsh.name/fix-javascript-errors

// JavaScript - Error and exception handling:

JavaScript language defines seven types of built-in error objects:
1. Error: This "Error" type is used to represent a generic exceptions. This is 
   often used to implement user defined exceptions.  is the most generic built-in 
   type of error.
2. RangeError: "RangeError" are generated by numbers that fall outside of a 
   specified range.
3. ReferenceError: A "ReferenceError" exception is thrown when a non-existent 
   variable is accessed. These exceptions commonly occur when an existing 
   variable name is misspelled.
4. SyntaxError: A "SyntaxError" is thrown when the rules of the JavaScript 
   language is broken.
5. TypeError: A "TypeError" exception occurs when a value is not of expected 
   type. Attempting to call a non-existent object method is a common cause of 
   this type of exception.
6. URIError: A "URIError" exception is thrown by methods such as encodeURI() 
   and decodeURI() when they encounter a malformed URI.
7. EvalError: An "EvalError" exception are thrown when the eval() function is 
   used improperly.

var error = new Error("Error message");

There is no restriction on the type of data that can be thrown as an exception:

throw true;
throw 5;
throw "error message";
throw null;
throw undefined;
throw {};
throw new SyntaxError("useful error message");

While the "throw" statement can be used with any data type, there are certain 
benefits to using it with the built-in exception types. Firefox, for example, 
gives special treatement to those objects by adding debugging information such 
as the filename and line number where the exception occurred.

The throw statement raises an exception. If the throw statement is in a try 
block, then control goes to the catch clause. Otherwise, the function invocation 
is abandoned and control goes to the catch clause of the try in the calling 
function. The expression is usually an object literal containing a "name" 
property and a "message" property. The catcher of the exception can use that 
information to determine what to do.

var add = function (a, b) {
  if (typeof(a) !== 'number' || typeof(b) !== 'number') {
    throw {
      name: 'TypeError',
      message: 'add needs numbers'
    };
  }
  return a + b;
}

The throw statement interrupts execution of the function. It should be given an 
exception object containing a name property that identifies the type of the 
exception, and a descriptive message property. You can also add other properties. 
The exception object will be delivered to the catch clause of a try statement.

To handle an exception, use the try, catch, and finally clause.

try {
  // Code to be executed
} catch (exception) {
  // This code handle the exception
  // Here we can inspect exception.name, exception.message, exception.line, 
  // exception.file, etc
  if (exception instanceof TypeError) {
  } else if (exception instanceof ReferenceError) {
  } else if (exception.name == "...") {
  } else if (exception.message == "...") {
  } else {
  }
} finally {
  // This code always get executed
}

The try clause must be followed by one or both of the "catch" and "finally" 
clauses.  The "finally" clause is also executed even if the "try" or "catch" 
clause executes a "return" statement.   For example, the following function 
returns false because the “finally” clause is the last thing to execute.

function foo() {
  try {
    return true;
  } finally {
    return false;
  }
}

The try statement executes a block and catches any exception that were thrown 
by the block. The catch clause defines a new variable that will receive the 
exception object.

We can create new exception types by extending the existing "Error" type. 
Because the new type inherits from "Error", it can be used like the other 
built-in exception types.

function DivisionByZeroError(message) {
  this.name = "DivisionByZeroError";
  this.message = message || "";
}
DivisionByZeroError.prototype = new Error();
DivisionByZeroError.prototype.constructor = DivisionByZeroError;

Common errors:

var cc_options = {
  'iframe': url,
};

For the above code, IE will produce an error "Expected identifier, string, or 
number", and Firefox will not.

The browser may throw the 'Unspecified Error' if:

1. You try to update the DOM with a string that are not valid HTML (not 
   appropriately quoted), especially if this HTML contains JavaScript.
2. When using the insertAdjacentHTML method to insert script, you must 
   include the DEFER attribute in the script element
3. Make sure that you are not doing any DOM manipulation until the DOM is 
   actually ready.
4. You cannot insert text while the document is loading. Wait for the onload 
   event to fire before attempting to call this method. If you are working with 
   frames, make sure that DOM inside the frame is ready you modify it.
5. You are doing DOM manipulation when the DOM is being unloaded somehow.

'ReferenceError: varInFunction is not defined'
null has no property
Uncaught TypeError: Object [object global] has no method 'specialFunction'

// Error handling:
The onerror event handler provides three pieces of information to identify the 
exact nature of the error:
1. Error message − The same message that the browser would display for the given 
   error.
2. URL − The file in which the error occurred.
3. Line number − The line number in the given URL that caused the error.
// Some modern browsers should provide the .stack property which contains the
// stack trace of the error.

function handleError(message, url, line) {
    return true;   // browser does not display the standard error message
    return false; // browser display the standard error message 
}
if (window.location.host.search(/clinicalcafe/) > -1) {
    window.onerror = handleError;
}

window.addEventListener('error', function (e) {
  var error = e.error;
  console.log(error);
});

The stack property in the error object is not part of the standard yet, but it 
is consistently available in the latest browsers. 

window.addEventListener('error', function (e) {
  var stack = e.error.stack;
  var message = e.error.toString();
  if (stack) {
    message += '\n' + stack;
  }
  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/log', true);
  xhr.send(message);
});

How can we suppress errors:

function handleError(message, url, line) {
    return true;   // browser does not display the standard error message
    return false; // browser display the standard error message 
}
if (window.location.host.search(/clinicalcafe/) > -1) {
    window.onerror = handleError;
}

What are the seven types of built-in error objects?

JavaScript language defines seven types of built-in error objects:

  1. Error: This "Error" type is used to represent a generic exceptions. This is often used to implement user defined exceptions.
  2. RangeError: "RangeError" are generated by numbers that fall outside of a specified range.
  3. ReferenceError: A "ReferenceError" exception is thrown when a non-existent variable is accessed. These exceptions commonly occur when an existing variable name is misspelled.
  4. SyntaxError: A "SyntaxError" is thrown when the rules of the JavaScript language is broken.
  5. TypeError: A "TypeError" exception occurs when a value is not of expected type. Attempting to call a non-existent object method is a common cause of this type of exception.
  6. URIError: A "URIError" exception is thrown by methods such as encodeURI() and decodeURI() when they encounter a malformed URI.
  7. EvalError: An "EvalError" exception are thrown when the eval() function is used improperly.

What is the most generic built-in type of error objects?

Error

How can we use the generic built-in type Error object?

var error = new Error("Error message");

The "Error" objects contains two properties, "name" and "message"

What are the two properties of the built-in Error object?

The "Error" objects contains two properties, "name" and "message"

How can we use try / catch?

try {
    // Code to be executed
} catch (exception) {
    // This code handle the exception
    // Here we can inspect exception.name, exception.message, exception.line, exception.file, etc
} finally {
    // This code always get executed
}

The try clause must be followed by one or both of the "catch" and "finally" clauses.

Complex applications can generate a variety of exceptions. In such cases, the "instanceof" operator can be used to differentiate between the various types of exceptions (TypeError, ReferenceError, etc):

try {
    // Some code
} catch (exception) {
    if (exception instanceof TypeError) {
    } else if (exception instanceof ReferenceError) {
    } else {
    }
}

Note that the "finally" clause is also executed even if the "try" or "catch" clause executes a "return" statement.

The try statement executes a block and catches any exception that were thrown by the block. The catch clause defines a new variable that will receive the exception object.

Is there any restriction on the type of data that can be thrown as an exception?

No. There is no restriction on the type of data that can be thrown as an exception:

throw true;
throw 5;
throw "error message";
throw null;
throw undefined;
throw {};
throw new SyntaxError("useful error message");

While the "throw" statement can be used with any data type, there are certain benefits to using it with the built-in exception types. Firefox, for example, gives special treatement to those objects by adding debugging information such as the filename and line number where the exception occurred.

The throw statement raises an exception. If the throw statement is in a try block, then control goes to the catch clause. Otherwise, the function invocation is abandoned and control goes to the catch clause of the try in the calling function. The expression is usually an object literal containing a "name" property and a "message" property. The catcher of the exception can use that information to determine what to do.

var add = function (a, b) {
    if (typeof(a) !== 'number' || typeof(b) !== 'number') {
        throw {
            name: 'TypeError',
            message: 'add needs numbers'
        };
    }
    return a + b;
}

The throw statement interrupts execution of the function. It should be given an exception object containing a name property that identifies the type of the exception, and a descriptive message property. You can also add other properties. The exception object will be delivered to the catch clause of a try statement.

How can we create new exception types or custom exception types?

We can create new exception types by extending the existing "Error" type. Because the new type inherits from "Error", it can be used like the other built-in exception types.

function DivisionByZeroError(message) {
    this.name = "DivisionByZeroError";
    this.message = message || "";
}
DivisionByZeroError.prototype = new Error();
DivisionByZeroError.prototype.constructor = DivisionByZeroError;

Why does IE throws the 'Unspecified Error'?

This error may happen if:

  1. You try to update the DOM with a string that are not valid HTML (not appropriately quoted), especially if this HTML contains JavaScript.
  2. When using the insertAdjacentHTML method to insert script, you must include the DEFER attribute in the script element
  3. Make sure that you are not doing any DOM manipulation until the DOM is actually ready.
  4. You cannot insert text while the document is loading. Wait for the onload event to fire before attempting to call this method. If you are working with frames, make sure that DOM inside the frame is ready you modify it.
  5. You are doing DOM manipulation when the DOM is being unloaded somehow.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License