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

The throw statement allows you to create a custom error.

Technically you can throw an exception (throw an error).

The exception can be a JavaScript String, a Number, a Boolean or an Object:

throw "Too big";    // throw a text
throw 500;          // throw a number
try { 
    if(x == "") throw "empty";
    if(isNaN(x)) throw "not a number";
    x = Number(x);
    if(x < 5) throw "too low";
    if(x > 10) throw "too high";
} catch(err) {
    message.innerHTML = "Input is " + err;
} finally {
    document.getElementById("demo").value = "";
}

Modern browsers will often use a combination of JavaScript and built-in HTML validation, using predefined validation rules defined in HTML attributes:

<input id="demo" type="number" min="5" max="10" step="1">

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.

Mozilla and Microsoft defines some non-standard error object properties:

  • fileName (Mozilla)
  • lineNumber (Mozilla)
  • columnNumber (Mozilla)
  • stack (Mozilla)
  • description (Microsoft)
  • number (Microsoft)

Do not use these properties in public web sites. They will not work in all browsers.

Error Name Values

  • EvalError: An error has occurred in the eval() function
    • Newer versions of JavaScript does not throw any EvalError. Use SyntaxError instead.
  • RangeError: If you use a number that is outside the range of legal values.
  • ReferenceError: If you use (reference) a variable that has not been declared.
  • SyntaxError: If you try to evaluate code with a syntax error.
  • TypeError: If you use a value that is outside the range of expected types.
  • URIError: If you use illegal characters in a URI function encodeURI().

Yonggoo Noh

I am interested in Computer science and Mathematics.