codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🌐

JavaScript

39 / 65 topics
39JavaScript try...catch...finally40JavaScript throw Statement41JavaScript Error Objects42JavaScript "use strict"43Debugging JavaScript
Tutorials/JavaScript/JavaScript try...catch...finally
🌐JavaScript

JavaScript try...catch...finally

Updated 2026-05-12
20 min read

JavaScript try...catch...finally

In the world of programming, encountering errors is inevitable. Errors can occur due to various reasons such as invalid user input, unexpected data formats, or network issues. Handling these errors gracefully is crucial for building robust and user-friendly applications. In JavaScript, the try...catch...finally statement provides a structured way to handle runtime errors.

Introduction

The try...catch...finally statement in JavaScript allows you to test a block of code for errors while it is being executed. The try block lets you write code that might throw an error, and the catch block lets you handle the error. Additionally, the finally block contains code that will execute regardless of whether an error was thrown or not.

This mechanism ensures that your program can continue running even if something goes wrong during execution. It's a fundamental tool for error handling in JavaScript applications.

Core Content

The Basic Syntax

The basic syntax of the try...catch...finally statement is as follows:

JavaScript
1try {
2// Code that might throw an error
3} catch (error) {
4// Code to handle the error
5} finally {
6// Code that will execute regardless of whether an error was thrown or not
7}

How It Works

  1. Try Block: The code inside the try block is executed first.
  2. Catch Block: If an error occurs in the try block, the control is immediately transferred to the catch block, where you can handle the error.
  3. Finally Block: Regardless of whether an error was thrown or not, the code inside the finally block will execute after the try and catch blocks.

Example 1: Basic Error Handling

Let's start with a simple example to understand how try...catch...finally works.

basicErrorHandling.js
1try {
2let result = 10 / 0;
3console.log(result);
4} catch (error) {
5console.error("An error occurred:", error.message);
6} finally {
7console.log("Execution completed.");
8}
Output
An error occurred: Division by zero
Execution completed.

In this example, dividing by zero throws a RangeError. The catch block catches this error and logs an appropriate message. The finally block executes regardless of the error.

Example 2: Handling Different Types of Errors

You can also handle different types of errors separately using multiple catch blocks.

multipleCatchBlocks.js
1try {
2let result = JSON.parse("{bad json}");
3console.log(result);
4} catch (syntaxError) {
5console.error("Syntax error:", syntaxError.message);
6} catch (error) {
7console.error("An unexpected error occurred:", error.message);
8} finally {
9console.log("Execution completed.");
10}
Output
Syntax error: Unexpected token b in JSON at position 1
Execution completed.

In this example, the JSON.parse method throws a SyntaxError because of invalid JSON. The first catch block handles this specific type of error, while the second catch block is a general error handler for any other types of errors.

Example 3: Using Finally Block

The finally block is useful for executing cleanup code, such as closing files or releasing resources, regardless of whether an error was thrown.

finallyBlock.js
1try {
2let file = openFile("data.txt");
3// Process the file
4} catch (error) {
5console.error("Error processing file:", error.message);
6} finally {
7closeFile(file);
8console.log("File closed.");
9}
Output
Error processing file: File not found
File closed.

In this example, even if an error occurs while opening the file, the finally block ensures that the file is closed properly.

Common Mistakes

  1. Omitting the Catch Block: Always include a catch block to handle errors. If you omit it, any unhandled exceptions will propagate up the call stack.
  2. Ignoring Errors in Finally: Be cautious when using return, break, or continue statements inside the finally block as they can override the normal flow of control.

Practical Example

Let's create a practical example that demonstrates error handling in a real-world scenario. We'll write a program that reads user input, processes it, and handles any errors gracefully.

practicalExample.js
1function getUserInput() {
2// Simulate user input
3return prompt("Enter a number:");
4}
5
6function processNumber(num) {
7if (isNaN(num)) {
8 throw new Error("Invalid input: not a number");
9}
10return num * 2;
11}
12
13try {
14let userInput = getUserInput();
15let result = processNumber(userInput);
16console.log(`The result is ${result}`);
17} catch (error) {
18console.error(error.message);
19} finally {
20console.log("Thank you for using the program.");
21}
Output
Enter a number: abc
Invalid input: not a number
Thank you for using the program.

In this example, the getUserInput function simulates user input. The processNumber function checks if the input is a valid number and throws an error if it's not. The try...catch...finally structure ensures that any errors are caught and handled gracefully, while the final message is always displayed.

Summary

  • Try Block: Contains code that might throw an error.
  • Catch Block: Handles the error thrown by the try block.
  • Finally Block: Executes regardless of whether an error was thrown or not, used for cleanup tasks.
  • Use multiple catch blocks to handle different types of errors.
  • Be cautious with control flow statements inside the finally block.

What's Next?

In the next topic, we will explore how to throw custom errors using the throw statement. Understanding how to throw and catch errors is essential for building robust applications that can handle unexpected situations gracefully.


PreviousJavaScript SymbolsNext JavaScript throw Statement

Recommended Gear

JavaScript SymbolsJavaScript throw Statement