Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
Syntax
As we are now clear with the definition of try/catch, and finally, let's check out their syntaxes.
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);
}
You can also try this code with Online Javascript Compiler
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.");
}
You can also try this code with Online Javascript Compiler
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:
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");
}
You can also try this code with Online Javascript Compiler
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);
}
You can also try this code with Online Javascript Compiler
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.
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 problems, interview experiences, and interview bundles for placement preparations.
However, you may consider our paid courses to give your career an edge over others!