Skip to main content

Command Palette

Search for a command to run...

Error Handling in JavaScript: Try, Catch, Finally

A beginner-friendly guide to handling runtime errors gracefully in JavaScript using try, catch, and finally

Updated
3 min read
Error Handling in JavaScript: Try, Catch, Finally
P
IT graduate 2024. Learning software and web development in public. Writing about bugs, fixes, small projects, useful tools, and lessons from building things step by step.

Introduction

JavaScript code does not always run perfectly.

Sometimes:

  • the wrong variable gets used

  • an invalid value appears

  • an unexpected situation occurs

Errors can happen in all of these situations.

And if errors are not handled, the program can feel like it fails abruptly.

This is where error handling becomes useful.


What Errors Are in JavaScript

In simple words, an error is an unexpected problem that happens during code execution.

Example:

console.log(userName);

If userName is not defined at all, a runtime error can happen.


Why Error Handling Matters

Error handling matters because:

  • the app feels less crash-prone

  • debugging becomes easier

  • graceful failure becomes possible

  • the user experience becomes better


Using try and catch

try {
  console.log(userName);
} catch (error) {
  console.log("Something went wrong");
}

Here:

  • try -> the risky code

  • catch -> handle the problem


Runtime Error Example

try {
  let user = null;
  console.log(user.name);
} catch (error) {
  console.log("Error caught:", error.message);
}

The finally Block

The idea of the finally block is simple:

whether an error happens or not, this block will run

try {
  console.log("Trying...");
} catch (error) {
  console.log("Error happened");
} finally {
  console.log("This always runs");
}

Throwing Custom Errors

function checkAge(age) {
  if (age < 18) {
    throw new Error("Age must be 18 or above");
  }
  return "Access granted";
}
try {
  console.log(checkAge(16));
} catch (error) {
  console.log(error.message);
}

A Simple Practical Example

function bootNavigation(mapLoaded) {
  try {
    if (!mapLoaded) {
      throw new Error("Map was not loaded");
    }
    return "Navigation ready";
  } catch (error) {
    console.log("Navigation failed:", error.message);
  } finally {
    console.log("Navigation sequence completed");
  }
}

bootNavigation(false);

Summary

  • errors are unexpected problems that happen during JavaScript execution

  • try is used for risky code

  • catch handles the error

  • finally always runs

  • throw can be used to create custom errors

  • error handling is important for both graceful failure and debugging


Final Thought

It is easy to ignore error handling, but in real applications it is a very important skill.

Once try, catch, and finally become clear, code starts to feel much safer and more predictable.


Continue Reading