JavaScript Error Handling β Try, Catch, Throw, Finally
Tanvir Ahmed
Posted on October 12, 2024
Error handling in JavaScript is important to deal with mistakes or problems that happen while your code is running. JavaScript gives you a few simple tools to handle errors and keep your code from crashing:
try: You use this to test a piece of code. If everything works fine, it runs without issues.
catch: If something goes wrong in the "try" part, the "catch" block will handle the error and stop the program from crashing.
throw: This is used to create your own errors. You can decide when to throw an error based on certain conditions.
finally: This block of code always runs, whether there's an error or not. It's useful for cleaning up resources, like closing a file or stopping a process.
Basic Structure:
Try & Catch:
In this JavaScript code, the try...catch block is used to handle potential errors that might occur when the code is executed. Here's what happens step-by-step:
Try Block
console.log("hello Tanvir");
This line executes successfully, printing hello Tanvir to the console.
console.log(num);
This line attempts to log the value of the variable num. Since num is not defined anywhere in the code, JavaScript throws a ReferenceError.
A ReferenceError occurs when code references a variable that hasn't been declared.
console.log("run");
This line would execute if no error occurred above it. However, because of the ReferenceError on the previous line, this line is never reached. As a result, run is not logged to the console.
catch Block
i. When the error occurs in the try block, control is passed to the catch block.
ii. The catch block receives the error object, which provides information about the error.
iii. error.name contains the type of error, which is "ReferenceError" in this case.
iv. error.message provides a description of the error, specifically "num is not defined".
as a result
Finally:
The try...catch...finally statement in JavaScript is used for exception handling. The try block contains code that may throw an error, the catch block handles that error, and the finally block executes code after the try and catch blocks, regardless of whether an error occurred or not.
Example with No Error
Throw:
The throw statement in JavaScript is used to create a custom error or to re-throw an existing error within a try...catch block. You can use throw to signal that something unexpected has happened in your code.
Posted on October 12, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.