Exception Handling in JavaScript, for Beginners !! ๐Ÿ™ˆ

Exception Handling in JavaScript, for Beginners !! ๐Ÿ™ˆ

ยท

6 min read

Overview of Exception Handling in JavaScript

JavaScript is one of the most widely used programming language over the globe. Therefore, many developers enjoy writing code and in recent times JavaScript has expanded into different usages with the increase in its versatility. Therefore, Exception Handling is a crucial aspect of programming like any other programming language. It is nothing but the exceptions are the Error that usually occurs and they way the steps we take to tackle this errors and their abnormal behaviour are known as the Exception Handling.

Exception Handling is the process of managing Error Handling errors that often occurs during the execution of the JavaScript Programming. For different Programming languages there are different ways and keywords to handle the issues occured due to errors. In JavaScript exceptions can be caused by a variety of factors such as incorrect user input, network errors, or unexpected behaviours of other third party packages/libraries.

So, in this blog let's us discuss about the different ways to handle the Exception of the Errors.

Hope, you are having a great learning about the Exception Handling.

Ways to Handle Error in brief :

In JavaScript, developers use try-catch blocks to handle exceptions. The try block contains the code thatt may cause an exceptions, while the catch block handles the exception if it occurs.

try {
// statement 
} catch(error) {
// statement of the exception
}

In the above example given, if an exception occurs within the try block JavaScript will immediately jump to the catch block and execute the code within it. If in-case there is error object it automatically sends it to the catch block contains information about the exception, such as its type and message.

Example 1:

How to make use of the try-catch block in JavaScript

// let's us try to divide the numbers by 0 and see how it is handled.

try {
let answer = 10/0;
} catch(error) {
    console.log('An Error occurred: ' + error.message);
}

In the above example the operation we are performing is invalid and therefore, it is automatically thrown into the catch block to execute and log the error.

Example 2 :

Now, let us peep into the other example

const student = {
    name: 'santos',
    class: 'II',
    age: '6'
}

try{
    let location = student.location.place;
} catch(error) {
    console.log('You have an Error : ' + error.message);
}

In the above example , we can clearly understand the code that we are trying to access the value or data which is not available in the object. So, the catch block automatically handles the error.

It is important to keep a few best practices for using try-catch block in JavaScript and they are listed below ::-

  1. Only catch exceptions that you can handle: Catching every possible exception can make it defficult to debug the code and also can lead to unexpected behaviour.

  2. Avoid catching generic exception : Catching generic exceptions, such as Error or Exception, can make it difficult to debug your code and can also lead to unexpected behaviour. Instaed, catch only only specific exceptions.

  3. Provide helpful error messages : When an exception is caught, provide a helpful error messages that explains the prolem and suggests the solution. This can help other developers understand what went wrong and how to fix it.

  4. There is also a keyword called finally which irrespective of error it also gets executed and it can be used for cleanup. It acn perform task such as closing database connections or releasing resources. This ensures that your code is robust and reliable.

Let us also learn how to use Throw statement to handle Error.

Example 1 : Throwing a custom Error.

if(inp === null) {
    throw new Error('Data input Invalid: null not allowed. ')
}

In the above example we are manually handling the error if the input value is null. The message will be displayed in the console.

Example 2 :

Throwing an Error with a custom object

let customError = {
    name: 'Custom Error',
    message: 'This is a custom error message'
}
try {
    throw customError;
} catch(error) {
    console.log(error.name + ' : ' + error.message);
}

In the above example of the code we are throwing a custom error object and catching it with a try-catch block. When the error is caught, we log the error name and message it to the console.

Example 3 :

Throwing an error with a specific type.

class MyError extends Error {
constructor(message) {
        super(message);
        this.name = 'MyError';
    }
}
try {
    throw new MyError('This is a custom error message.');
} catch(error) {
    console.log(error.name + ' : ' + error.message)
}

Overview of the Error types in JavaScript

  • Error : the base class for all built-in error types

  • Syntax Error occurs when there is a syntax error in the code.

{
let x = 1;

// Here the closing bracket is missing. Any error related to syntax.
  • ReferenceError : It occurs when an undefined variable is referenced.
function foo() {
  'use strict';
  bar = true; //variable not declared
}

foo();
// What you get after executing above program?? An Error??

  • Runtime Errors : This type of errors often occurs during the execution of the program due to unexpected input or network issues. As this types of errors can be caused due to various factors. this type of errors cannot be caught during the complilation phase.
let a = b;

// Here  and there

The above given examples of errors can be handled with try-catch block. This blocks will will let the specific try of codes to pass through them in various cases such as like when it return an response then it passes through the try block and if there is an error it is then passed to the catch block along with it, the error object helps us to get the information about the error.

One of the most efficient way to handle the Error other than try-catch block is given in the below examples ::

let count = 0;

function fetchTheData(){
    return fetch('https://getdata.com/data')
    .then(res => res.json())
    .catch(err => {
        if(count < 5){
        count++
        return fetchTheData();
        } else {
            throw new Error('Failed to retrieve data after 5 attempts');
        }
    })
}

So, in the the given example we are handling the error if the error occurs and repeating the catch for 5 times and still , if it is unable to return us the error, iot will return us custom Error.

TD;LR:

  • Handling of Error in javaScript is necessary to handle some unexpected error in our code which is the best practice to follow in order to get rid of the untoward consequences.

  • try-catch block helps us to handle the error without much hustle.

  • then-catch is also one of the ways to handle the error unexpectedly.

Hope you enjoyed reading the article, please leave a comment for your valuable feedback ๐Ÿ’

ย