How to Handle Errors and Exceptions in JavaScript

ADMEC Multimedia Institute > Web Design > How to Handle Errors and Exceptions in JavaScript

Like every programming language, JavaScript has its error management mechanism. To write a good program and develop an application, the code must be error free  and ready to handle the exceptions as these are very primary tasks which one should learn during the JavaScript classes.

For some errors that we encounter on executing our code can be resolved with the help of debugging in JavaScript which we will look into in the coming lesson.

Understanding Errors and Exceptions in JavaScript

ERROR is the event that occurs during the time of code execution and disturb the normal flow of code which results into creation of an exception object.

An object which has been created by event is an exception, which also known as an error.  

Errors and exceptions are caused due to failure of resources or user error or programming logic failure etc. It depends on the code(how the code is written) that error will occur or not and no dependency is there for the errors on the purpose of the written code.

Errors are of 3 types:

  • Syntax Errors
  • Runtime Errors
  • Logical Errors

Syntax Errors

Syntax errors, also called parsing errors, occur due to incomplete or incorrect code statements or in some cases statements that do not follow syntactical rules. It arises on compile time where compiler is used but in JavaScript, Interpreter is used,so it occurs on interpretation time.

Example:

<script type="text/javascript">
     document.write(;
     var x = 'It's a beautiful day';
</script>

The above error occurs because of missing parenthesis.

When syntax error occurs, only that thread is affected which contain the code caused to error occurance and other threads get executed normally if no code is there which depends on the code containing the error.

Some common syntax errors are below:

Missing Matched Parenthesis or Brackets
Ex. window.print(;

Missing Matched Quotes
Ex. var x = 'It's a beautiful day';

Runtime Errors

Runtime errors occurs at the time of code execution and the system cannot execute it. These errors occur during the execution of program or we can say at the time of compilation/interpretation (Depends on which is used by the language compiler/interpreter. In case of JavaScript, It is interpreter).

These are also known as EXCEPTIONS.

Example: In this e.g. the syntax is correct but the following code causes an error at runtime because it is trying to call a method that does not exist.

<script type=”text/javascript”>

The thread which consists the exceptions also effected. It allows other threads to continue the normal execution.

Some common error occurs at runtime:

In this statement,there is an error because JavaScript is a Case sensitive language.
Ex.  GetElementByTag ();

Refer functions or DOM objects without their existance.
Ex. <BODY onload="loadData();>

Reserved word is using
Ex. var for = 5;

Missing parameter is using

LOGICAL ERRORS

A logical error is an error in the program which occurs when we implement not a right logic. It does not terminate the program unexpectedly. It produces unintended or unwanted result or other output. It is difficult to track these errors as they vary from programmer to programmer and also on your business logic.

A program can be executed normally if logical errors are in existence but the only difference is Output is not according our desire. We will know to a logical error when the output is unwanted.

Such errors can be tracked down using Debugging tools.

Example:

This function which is intended to calculate the average of two numbers contains a logical error: It is missing parentheses in the calculation, so it compiles and runs but does not give the expected answer due to operator precedence (division is evaluated before addition).

function average(a,b)
{
return a + b / 2;     /* should be (a + b) / 2 */
}

So here if I try to pass 3,3 as my input it will output 4.5; which is incorrect, because according to the logic above a+b/2 will first divide value in ‘b’ by 2 and then add value from ‘a’ because of the precedence. So, the desired output is incorrect because of a logical error.

Handling Exceptions in JavaScript

When a function cannot proceed normally, what we would like to do is just stop what we are doing and immediately look back to a place from where we can handle the problem. This is what exception handling does.

Exception handling is a mechanism that makes it possible for code that runs into a problem to raise an exception, which is simply a value. Raising an exception is similar to a return from a function: it jumps out of not just the current function but also out of its callers, all the way down to the first call that started the current execution.

Let’s look at the “ERROR object” in JavaScript and its role:

Error Object In JavaScript

When an exception occurs, an object representing the error is created and thrown. “Error” objects contain two properties:

  1. Name:      this property specifies the type of exception.
  2. Message: this property provides a more detailed description of the exception.  The “message” gets its value from the string passed to the exception’s constructor.

ERROR NAME VALUES:

  1. RangeError:         A number “out of range” has occurred
  2. ReferenceError:   An illegal reference has occurred
  3. SyntaxError:        A syntax error has occurred
  4. TypeError:           A type error has occurred
  5. URIError:             An error in encodeURI() has occurred     

For exception handling JavaScript provides the following set of statements:

  • Try
  • Catch
  • Finally
  • Throw

TRY CATCH

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Syntax:

try {
Block of code to try
}
catch(err) {
Block of code to handle errors
}

Here in the try block we add our business logic, and if an error occurs the steps we want to take are written in the catch block depending upon the error, which is indicated by the error object in JavaScript.

Example:

try {
aalert("Welcome guest!");
}
catch(err) {
console.log(err.message);
}

Here we have misspelled alert as ‘aalert’, which will be caught as an exception and handled in the catch block.

FINALLY

The finally statement lets you execute code, after try and catch, regardless of the result.

Syntax:

try{
Block of code to try
}
catch(err) {
Block of code to handle errors
}
finally {
to be executed regardless of the try / catch result
}

  Example:

function myFunc()
{
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.message );
}
finally {
alert("Finally block will always execute!" );
}
}

The finally block of code is executed regardless of the try and catch, it is also used for resetting values or initializing them

THROW

The throw statement allows you to create a custom error. We can throw an exception (throw an error) using this statement. The exception can be a JavaScript String, a Number, a Boolean or an Object:

Example:

throw "Too big";    // throw a text
throw 500;          // throw a number

If we use throw with try and catch we can control program flow and generate custom error messages.

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;
}

In the tutorial above we have read about errors in JavaScript and mechanisms to handle them. As writing a error free code is very essential for every web designer or developer. If the code contains errors then you won’t be able to develop an amazing program or application. Hope you’ll get assistance from this tutorial in handling errors in JavaScript.

To read more such types of blogs please go through our JavaScript blogs section and find your favorite blog there.

Related Posts

Leave a Reply

Talk to Us