Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is a try...catch Block in JavaScript?
3.
Syntax
4.
Flow Chart ​​of the try...catch Statement
5.
Sample Examples
5.1.
Simple Try-Catch
5.2.
Function Call in Try-Catch
5.3.
Function Call in Try-Catch-Finally
5.4.
Try-Catch in HTML
6.
Throw Keyword
7.
Nested Try-Catch Blocks
8.
Frequently Asked Questions
8.1.
What is the difference between try catch and try except?
8.2.
When should you use a try catch?
8.3.
Can I use try without catch?
8.4.
How does a try catch work?
9.
Conclusion
Last Updated: Mar 27, 2024
Easy

Try Catch in Javascript

Author Sagar Mishra
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

In the dynamic and ever-evolving world of web development, JavaScript stands as the backbone of interactive and user-friendly applications. As developers, we strive to create seamless and robust code that not only delivers a smooth user experience but also gracefully handles unexpected issues. Enter the try-catch statement, a fundamental tool in JavaScript's arsenal for effective error handling.

try catch in javascript

This blog will discuss the topic of try-catch in Javascript. If you are new to JavaScript, going through the Introduction to Javascript is suggested.

What is a try...catch Block in JavaScript?

The try is a block of statements where we can write the code until an exception is thrown. We write the codes that need to be tested in the try block, and if the compiler gets any kind of error, it passes the situation to the catch block.

The catch is a block of statements which will execute after getting an error or exception in the try block. We use a catch block so that it can handle the errors by running the statements inside the catch block.

There is one more statement in the try/catch blocks: finally. The "finally" statement comes in the last. The code in the "finally" block runs after the complete execution of the try/catch blocks. This block of code will run regardless of any errors or exceptions.

Here note that the catch and finally blocks are optional.

Let's break down each part:

  • try{} statement: In the try block, you put the code that might have errors. If there's an error, it goes to the catch block to deal with it. If everything goes well without errors, it just runs the code inside the try.
     
  • catch{} statement: The catch block deals with any errors that might happen in the try block. It runs a set of statements written inside it. This block has either a special set of instructions created by the programmer or a default set of instructions provided by the programming language. The catch block only runs if there's an error in the try block; otherwise, it gets skipped.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax

As we are now clear with the definition of try/catch, and finally, let's check out their syntaxes.

try {
    // Try block
} catch (exception variable) {
    // Catch block
} finally {
    // Finally block
}

Flow Chart ​​of the try...catch Statement

Let's look at the flow chart of the try/catch statement.

flow chart

In the above flow chart.

  • The program starts from the Start.
     
  • It will move to the try block and check whether the statements in the try block have any errors or not.
     
  • If yes, it will move to the catch block.
     
  • And if not, the program will end.

Sample Examples

We will now see some examples for better understanding.

Simple Try-Catch

// Try-Catch block
try {
    a();
} catch (error) {
    print("We got an error!");
    print("The error says: " + error);
}


Output:

output

Explanation:

As you can see in the above example, we have called the function a() in the try block, which is not declared. Hence, that statement should throw an error. We defined a catch block that prints a message and the error to catch this error.

Function Call in Try-Catch

// Creating a function
function a() {
    print("I am in the function");
}

// Try-Catch block
try {
    a();
} catch (error) {
    print("We got an error!");
    print("The error says: " + error);
}


Output:

output

Explanation:

In this example, we have declared the function a(). So, there is not any error in the code. Hence, the compiler ignored the catch block.

Function Call in Try-Catch-Finally

// Creating a function
function a() {
    print("I am in the function");
}
 
// Try-Catch and Finally block
try {
    a();
} catch (error) {
    print("We got an error!");
    print("The error says: " + error);
} finally {
    print("I am in the finally function.");
}


Output:

output

Explanation:

In this example, we have used the "finally" statement, and as discussed earlier, the Finally block runs irrespective of the result from the try-catch block. Hence, the code present in the "finally" block always runs.

Try-Catch in HTML

<html>
    <head>
        <title>Try-Catch Example</title>
    </head>
    <body>
        <script>
            // Try-Catch block
            try {
                // Using throw keyword
                throw new Error("We are in the throw statement");
            } catch (error) {
                // Printing error
                document.write(error.message);
            }
        </script>
    </body>
</html>


Output:

output

Explanation:

In this example, we tried to execute the program using an HTML web page. First, we entered the try block and then printed the output using the catch block.

Throw Keyword

As of now, we understand how to tackle the errors. But do you know we can also throw our custom errors as well? If not, then let's check this out.

There is a keyword "throw". Using this keyword, we can define the exception in the code. Also, we can throw any expression of the number, string, object, or even an object. Let's take an example for better understanding.

Example:

let age = 15;
// Try-Catch-Finally block
try {
    var names = ["Raj", "Pankaj", "Ram", "Rahul"];
    print(names);

    // Conditions
    if (age >= 18) {
        print("Ready for driving licence");
    } else {
        throw new Error("Not ready for driving licence");
    }
} catch (error) {
    print(error);
} finally {
    print("Driving Licence is compulsory");
}


Output:

output

Explanation:

In the above example, 

  • We took four students of the same age and printed them on the output screen. 
     
  • Next, we checked whether the age is greater than 18. 

    • If yes, then print the message ''Ready for driving licence''.
       
    • If not, throw the custom error ''Not ready for driving licence''.
       
  • At last, the finally block will run and print a message that says ''Driving Licence is compulsory''.

Nested Try-Catch Blocks

The concept of nested try block is the same as the other programming language. We will take a try block, and inside the same try block, we will again take a try block. Let's check an example for clarity.

Example:

// Nested Try-Catch block
try {
    try {
        // Using throw keyword
        throw new Error("Error detected!");
    } catch (error) {
        print("inner", error.message);
    } finally {
        print("I am in finally");
    }
} catch (error) {
    print("outer", error);
}


Output:

output

Explanation:

In this example, we used the nested try-catch block and the throw keyword. If you notice, we caught the error in the inner try block. Hence the code will stop at the inner catch block without moving to the outer catch block.

Frequently Asked Questions

What is the difference between try catch and try except?

In JavaScript, it's try-catch; in Python, it's try-except. They both serve the same purpose: handling errors in the try block.

When should you use a try catch?

Use try-catch when executing code that might generate errors. It helps gracefully handle exceptions and prevents the entire program from crashing due to unexpected issues.

Can I use try without catch?

Yes, you can use try without catch, but it's generally not recommended. It's better to catch and handle errors to ensure robust code.

How does a try catch work?

The code within the try block is executed. If an error occurs, the catch block is triggered, allowing you to handle and manage the error gracefully, preventing program crashes.

Conclusion

This article discusses the topic of the Try Catch in Javascript in detail. We have seen the definition, syntax, and flow chart. Along with this, we saw three sample examples with code, output, and proper explanation.

We hope this blog has helped you enhance your knowledge of the Try Catch in Javascript. If you want to learn more, then check out our articles. 

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But suppose you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, you may consider our paid courses to give your career an edge over others!

Previous article
Handling Errors in Javascript
Next article
Custom Errors
Live masterclass