How to Use IrfanView’s Built-In Effects for HTML5 and CSS3 Programming
10 Stellar Web Resources for HTML5 and CSS3
How to Create Cascading Style Sheets (CSS) Simply and Easily

How to Throw Errors in JavaScript to Program with HTML

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)
{
  try
  {
   // 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: " +
        arguments[i]);
     }
    
     // Add to the argument string.
     Result += arguments[i] + "<br />";
   }
  }
  catch(Err)
  {
   // Display the error onscreen and return.
   document.getElementById("Result").innerHTML =
     Err.name + "<br />" + Err.message;
   return;
  }
 
  // 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.

image0.jpg

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
How to Create a New JavaScript File in Komodo Edit
How to Register a Domain Name for Your HTML5 and CSS3 Site
How to Make Your HTML5 and CSS3 Site Live
How to Use HTML5 and JavaScript to Canvas Your Web Page
How to Choose Colors for Your HTML5 and CSS3 Based Web Pages
Advertisement

Inside Dummies.com