Open In App

How to re-write the code sample without try/catch block ?

Improve
Improve
Like Article
Like
Save
Share
Report

Errors almost certainly occur when executing JavaScript code. These problems can arise due to a programming error, incorrect input, or an issue with the program’s logic. However, all mistakes may be solved, and to do so, we have different statements but the most commonly used is “try and catch”.

However, if a method contains code that may produce an exception during execution, we generally surround that code with a try-catch block to handle the exception.

Example 1: Without using a try-catch statement

Javascript




console.log("Start of program");
helloWorld;
console.log("Another program execution");


Output:

Start of program
Uncaught ReferenceError: helloWorld is not defined

Example 2: Using a try-catch statement

Javascript




try {
    console.log("Start of program");
    helloWorld;
}
catch (err) {
    console.log("Error has occurred" + err.stack);
}
 
console.log("Another program execution");


Output:

Start of program
Error has occurred ReferenceError: helloWorld is not defined
Another program execution

In the above example, the method throws an exception during execution and because there is a try-catch block for exception handling, the program executes successfully without terminating abnormally!

1. When Is It Appropriate to Use Try-Catch?

The try-catch statement should be used if you wish to hide mistakes from the user or create custom errors for the benefit of your users and it also has the advantage of hiding too technical error messages from people who wouldn’t understand them anyhow.

Try-catch is best used in parts of your code when you think mistakes will occur that are out of your control for whatever reason.

2. When Should You Avoid Using Try-Catch?

If you know an error is likely to happen, you shouldn’t use the try-catch statement since you’d rather debug the problem than disguise it. 

Let us see an example to better understand this!

Example 1: Nested Try-Catch

Javascript




async function anyFunction() {
    try {
        const result = await fetch("http://author.com");
        try {
            const another = await fetch("http://huihuihui.com");
        } catch (anotherError) {
            console.log(anotherError);
        }
    } catch (e) {
        // Some other error handling
    }
    try {
        const anotherResult = await someOtherAsync();
    } catch (errorFromAnotherResult) {
        // Some other error
    }
}


Why there is a need to avoid writing too many try-catch statements?

Every day, developers write code that we need to double-check for flaws and you’re coding try/catch blocks all over the place to keep your program from crashing. Because you want to standardize your error management, you may go overboard at times.

Statements like “Try / Catch” abound… They can even be nested or chained at times due to which code becomes redundant and overpopulated with the same unnecessary code and you also don’t want to rely on the error format of external libraries (or customize it).

You’ll have to admit that this is tedious, repetitious, and dull.

But, as we’ll see below, by making a middleware (with a short piece of code), we can achieve something far greater and more powerful by encapsulating our asynchronous code into a simple middleware(or you can say utility function) to do this.

Let us see what’s happening inside of our code! But first, let’s have a look at our “getResult” function:

Javascript




async function getResult(num: number):
    Promise<number | Error> {
    if (num === 0) {
        throw new Error("Error found!")
    }
    return num;
}


Basically, this function takes a number and it will return a promise that either returns a number or an error. 

If the number is zero it will return the error or it will return a number.

Output:

Input: 0

Error found!

Input: 1

1

Now, to do this in a more functional way we have created the utility function named “tryToCatch” – this function takes a function and arguments and it will try to run our function in a try-catch block and it will return the error as null and then it will return the result of our function otherwise it will return an error.

Javascript




const tryToCatch = async (fn: Function, ...args: any) => {
    try {
        return [null, await fn(...args)];
    }
    catch (err) {
        return [err];
    }
};


Let’s refactor our code to use our new utility function to remove the try-catch block by wrapping our function in the utility function named “tryToCatch”

Example 1: Using traditional try-catch statement.

Javascript




async function run() {
    let result;
 
    try {
        result = await getResult(0);
    } catch (error) {
        console.log("Error handled");
    }
 
    console.log({ result });
};


Output:

Error handled

Example 2: Refactoring the same code using the utility function. 

Javascript




async function run() {
    const [error, result] = await tryToCatch(getResult, 1);
    if (error) {
        console.log(error);
        return error;
    }
    console.log({ result });
};


Output:

{result:1}

Now we can handle our error and can keep our result console log as normal. In addition to your usual try/catch blocks, you can now use that sequential-like style to handle errors.



Last Updated : 25 Mar, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads