How to Throw Errors in JavaScript to Program with HTML - dummies

How to Throw Errors in JavaScript to Program with HTML

By John Paul Mueller

There are times when you can’t handle an error in JavaScript or you can’t handle it in the location where the error occurs. Throwing an error means creating a new Error object that a try…catch block can handle. JavaScript doesn’t provide any sort of default error handling. It won’t tell the user something is wrong either. When working with JavaScript, you must provide the complete error-handling package.

function OptionalArgument(param)
   // Determine whether there were any params passed.
   if (arguments.length == 0)
     // Throw an error.
     throw new ReferenceError("No Data Supplied");
   // Create a string to hold the arguments.
   var Result = new String();
   // Process each of the arguments in turn.
   for (var i = 0; i < arguments.length; i++)
     // Verify that the argument is of the right type.
     if (typeof(arguments[i]) != 'string')
      throw TypeError(
        "Incorrect Data Supplied, type:" +
        typeof(arguments[i]) + " value: " +
     // Add to the argument string.
     Result += arguments[i] + "<br />";
   // Display the error onscreen and return.
   document.getElementById("Result").innerHTML = + "<br />" + Err.message;
  // Display the results onscreen.
  document.getElementById("Result").innerHTML = Result;

In this case, the example throws specific error types to make it possible for a developer using the function to find problems with input quickly. When the caller doesn’t provide a value or the value is of the incorrect type, the application throws a specific kind of error that tells the caller precisely what went wrong.


Always use specific errors when you can. However, you may encounter situations when none of the standard error types meet your needs. In this case, you can create a custom error type. This article describes how to create custom error types. You also find some additional information about the standard error types as part of that article.