JavaScript Error Handling — Try, Catch, Throw, Finally

Tanvir Ahmed - Oct 12 - - Dev Community

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:

Image description

Try & Catch:

Image description

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");
Enter fullscreen mode Exit fullscreen mode

This line executes successfully, printing hello Tanvir to the console.

console.log(num);
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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

Image description

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.

Image description

Example with No Error

Image description

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.

Image description

. . . . . .