There are four major error types in programming: compile errors, logic errors, input/validation errors, and runtime errors. Error catching in code is usually limited to the latter two types. It would be nice if you could handle your own logic errors at runtime, but sadly, there is no such code construct yet. As for syntax errors, an interpreted language like JavaScript won’t catch those until the script is loaded into and read by the browser. While you normally can’t catch syntax errors, as we’ll see shortly, there are times that you can. Today’s article will discuss the syntax error, along with two other error types, while the next installment will cover the remaining three.
The Six JavaScript Error Types
The JavaScript 1.5 specification defines six primary error types, as follows:
EvalError: Raised when the eval() functions is used in an incorrect manner.
RangeError: Raised when a numeric variable exceeds its allowed range.
ReferenceError: Raised when an invalid reference is used.
SyntaxError: Raised when a syntax error occurs while parsing JavaScript code.
TypeError: Raised when the type of a variable is not as expected.
URIError: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner.
Advertisement
The Error.name Property
The benefit of having all the different error types is that you can pinpoint more accurately what kind of error you’re dealing with. This is done using the Error.name property because JavaScript’s loose typing doesn’t support specifying which type you want to catch as you would in Java:
catch(ArrayIndexOutOfBoundsException e) {}
In JavaScript, you have to use an if statement within a single “catch” block:
I personally like to use a switch if I’m checking for several error types at once instead of ifs because the same error name property is evaluated every time.
Here’s an example that produces and catches a SyntaxError. The code execution is linked to a button click event using the eval() function. Although there is also an EvalError type, it doesn’t happen because the eval() is used correctly; it’s the code that’s dubious (notice the missing closing quote [“])! In fact, this error type is thrown pretty much exclusively from the eval() method because syntax errors stop code execution immediately. That means that you can often catch them in development and testing.
function captureSyntaxError() {
try {
eval('alert("Hello world)');
}
catch(error) {
if(error.name === 'SyntaxError') {
alert("caught a " + error.name + ": " + error.message);
//handle that error type
}
else {
alert("caught a " + error.name + ": " + error.message);
//handle generic errors here
}
}
}
This version also checks for an EvalError, so the if statement has been replaced by a switch. An EvalError is pretty rare as the only way to encounter it is to use the eval in any way other than a direct method call. So how do you do that? You can treat it like an object using the new keyword:
vary = new eval();
Setting it to a variable should also throw an EvalError:
eval = 'test';
You shouldn’t come across the EvalError all that often because Internet Explorer 8 and Firefox 4+ don’t seem to ever throw them! Both treat the first example as a TypeError and don’t mind setting eval to whatever you want, effectively clobbering it into oblivion!
function captureEvalError() {
try {
var sum = eval('function test(( { return 1 + 1; }');
alert("NO ERROR CAUGHT: Your browser doesn't seem to mind that we just set eval to the letter 'x'!");
} catch(error) {
switch(error.name) {
case'SyntaxError':
alert("caught a " + error.name + ": " + error.message);
//handle error…
break;
case'EvalError':
alert("caught a " + error.name + ": " + error.message);
//handle error…
break;
default:
alert("caught a " + error.name + ": " + error.message);
//handle all other error types here…
break;
}
}
}
Advertisement
The ReferenceError
Reference errors are one of the most common of all. They’re caused by referencing a variable that has not been declared first. For instance:
var tmp = x; //no x variable declared!
Before trying the next demo, be aware that Internet Explorer 8 does not handle these correctly either, throwing a TypeError instead.
function captureReferenceError() {
try {
var sum = x + y;
alert(sum);
} catch(error) {
switch(error.name) {
case'SyntaxError':
alert("caught a " + error.name + ": " + error.message);
//handle error…
break;
case'EvalError':
alert("caught a " + error.name + ": " + error.message);
//handle error…
break;
case'ReferenceError':
alert("caught a " + error.name + ": " + error.message);
//handle error…
break;
default:
alert("caught a " + error.name + ": " + error.message);
//handle all other error types here…
break;
}
}
}
Advertisement
Conclusion
Today we learned how to distinguish between different error types using the Error.name property as well as three of the six JS error types. In the next article, we’ll be covering the RangeError, TypeError, and URIError types.
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.
The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.
Advertiser Disclosure: Some of the products that appear on
this site are from companies from which TechnologyAdvice
receives compensation. This compensation may impact how and
where products appear on this site including, for example,
the order in which they appear. TechnologyAdvice does not
include all companies or all types of products available in
the marketplace.