Contact Information

KodeBlog

We're Available 24/ 7. Drop us an email.

JavaScript Exception Handling

Exceptions are errors that occur during runtime. For example, you may have try to access a function that does not exist and your code editor does not raise any exceptions because it expects the function to be loaded from else where or you just made a typing error.

Executing the code in that state give raise an error and halt your application. This is not something that you can handle during design time but you can do something about it during runtime. Exceptions allow us to gracefully handle errors as they occur without halting the entire application.

Topics to be covered

We will cover the following topics in this lesson

Lesson Prerequisites

For you to successfully complete this lesson, you should have the following requirements

  • NodeJS - we will be executing JavaScript files directly using NodeJS from the command line. Alternatively you can execute the files in the web browser but that takes a a little more time and involves working with multiple programs.
  • Web Browser - a web browser can be used as an alternative to executing JavaScript files that we will be working with.
  • Visual Studio Code - we will be using it as the code editor. It comes with a built-in terminal that will allow us to easily execute JavaScript code from within the text editor. You can also use any code editor that you prefer.
  • JavaScript Basics - this is an added advantage and not mandatory. We will explain every piece of code covered in these lessons.

Lesson Practical Examples Project Setup

This is a practical based lesson. For you to successfully work out the examples given in this lesson, you will need to setup the following directories and files

Create a new directory called javascript-catch

Open the directory javascript-catch in Visual Studio Code or your favorite code editor

Create the following files inside your project folder.

  • catch.js - this file will be used to for code dealing with the switch statement

The following visualizes our project setup

javascript-catch
-catch.js

Try catch syntax

The syntax for the try catch block is as follows

try{
	//do something that might potentially go wrong
}catch(error){
	//error handler
}

HERE,

  • try{...} encloses the code to be executed with the {...} curly brackets of the try statement. The code placed here has the potential to throw an error at runtime
  • catch (error) specifies what to do if the error occurs during runtime. The code placed here gracefully handles the error so that the application does not halt.

 

Try catch example

Let us now look at a practical example. We will create a simple program that tries to access a function that does not exists so that JavaScript throws an exception. We will then modify the code so that i can handle the exception gracefully.

Open the file catch.js and add the following code

let result = product(3,7);

console.log(result);

console.log('Exceptions are runtime errors');

HERE,

  • let result = product(3,7); defines a variable result that is assigned the return value of the function product. Note we have not defined the function product
  • console.log(result); prints out the result in the console.
  • console.log('Exceptions are runtime errors'); prints the regular string to the terminal

Open the terminal and execute the following command

node catch.js

You should be able to get the following error

let result = product(3,7);
             ^
ReferenceError: product is not defined

Notice the application stopped and the regular string has not been printed to the terminal. Now that we have seen what exceptions are, let us modify the above program and handle the exception gracefully.

try{
    let result = product(3,7);

    console.log(result); 
}catch(error){
    console.log('Application Error. Description: ' + error.message);
}

console.log('Exceptions are runtime errors');

HERE,

  • try{...} encloses the code that has the potential of throwing an error during runtime
  • catch(error){...} specifies the action that should be taken when a error occurs
  • console.log('Exceptions are runtime errors'); represents the code that should be executed regardless of whether an error occurs or not in the above code

Run the following node command

node catch.js

You should be able to get the following results

Application Error. Description: product is not defined
Exceptions are runtime errors

Notice our application didn't halt. When an exception occurred, we handled it gracefully and our application continued executing normally.

The error object

The error object has two properties namely

  • name - contains the name of the exception that occurred. The following list describes some of the commond exceptions

    • EvalError - is thron if an error occurs in the eval function
    • RangeError - is thrown when a given number is out of range. For example, trying to create a number with 1000 decimal points can throw this error
    • ReferenceError - occurs when you try to make reference to something that does not exist
    • SyntaxError - is thrown when a syntax error occurs.
    • TypeError - is thrown when a type error occurs
    • URIError - occurs when you have invalid URI characters and you call URI related functions
  • message contains the description of the error that occurred.

  • stack contains very detailed information about the error.

The following example shows you how to access the name and message properties of the error object.

try{
    let code = 'alert("alert does not exist in node, its a browser thing")';

    eval(code);
}catch(error){
    console.log('Error Name: ' + error.name);
    console.log('Error Message: ' + error.message);
}

HERE,

  • try{...} encloses our runtime prone code with the try block
  • let code = 'alert("alert does not exist in node, its a browser thing")'; defines a string variable code that contains valid JavaScript code but for the web browser and not NodeJS
  • eval(code); uses the eval function to execute the JavaScript string code
  • catch(error){...} defines the code that should gracefully handle any errors that may occur. error.name gives access to the type of Error while error.message gives us access to the error description.

Open the terminal and run the following command

node catch.js

You should be able to get the following error

Error Name: ReferenceError
Error Message: alert is not defined

Finally statement

The finally statement is used for containing code that should be executed regardless of what happens. For example, if you openned a file for processing, you need to close it whether it is processed succesfully or an exception occurs. This is where the finally statement comes in.

Let's now look at a practical example. Add the following code to our file catch.js

try{
    let code = 'alert("alert does not exist in node, its a browser thing")';

    eval(code);
}catch(error){
    console.log('Error Name: ' + error.name);
    console.log('Error Message: ' + error.message);
}finally{
    console.log('hey, i always show up error or not');
}

HERE,

  • finally{...} defines the code block to be executed regardless of whether we got an error or not.

Running the above code produces the following results.

Error Name: ReferenceError
Error Message: alert is not defined
hey, i always show up error or not

Throw statement

JavaScript also allows you to define your own custom errors. You do this using the throw statement. Technically, you are not supposed to divide a number by zero. Let us see how JavaScript handles that.

Add the following code to catch.js

let result = 8 / 0;

console.log(result);

HERE,

  • let result = 8 / 0; defines a variable result that is assigned the value of 8 divided by 0
  • console.log(result); logs the result to the console

Executing the above code gives us the following results

Infinity

That is not very helpful. So we will modify the program so that we check for division by zero then throw an error if that is the case. Modify the above program as follows

let first_number = 8;
let second_number = 0;

try{
    if (second_number == 0){
        throw new Error ('Division by zero exception. You cannot divide by zero')
    }
    let result = first_number / second_number;
    console.log(result);
}catch(error){
    console.log('Error Name: ' + error.name);
    console.log('Error Message: ' + error.message);
}

HERE,

  • if (second_number == 0){...} checks to see if the value of second_number is 0. if yes then an exception is raised using the throw statement. We are using new Error(...) to create an instance of the Error classing passing in a string argument that will be used as the error message.

Executing the above code should give you the following results

Error Name: Error
Error Message: Division by zero exception. You cannot divide by zero

As you can see, the above makes much more sense compared to returning infinity as the result.

Summary

Exceptions are error that ocur during runtime when the user is interacting with the application. Unhandled exceptions can cause the application to come to a halt. You can handle exceptions gracefully by using the try catch block. You can also define your own custom exception types by using the throw statement.

Author: Rodrick Kazembe

Rodrick is a developer who works on Desktop, Web and Mobile Applications. He is familiar with Python, Java, JavaScript, C++, C#, Kotlin, PHP, Python and the list goes on. Rodrick enjoys sharing knowledge especially when it comes to technology.

JavaScript While Loop

Leave A Reply