JavaScript Course Lesson 16 of 16
The Codex / JavaScript / Error Handling

Error Handling

try/catch/finally, the built-in Error types, throwing your own errors, and how to read a JavaScript error message.

What it is, in plain English: An error is JavaScript's way of telling you something went wrong — a file wasn't found, a network request failed, a user typed the wrong thing. Without error handling, a single error crashes your entire program. try/catch lets you catch an error and decide what to do: show a friendly message, try again, log it, or handle it gracefully. Reading and understanding JavaScript error messages is one of the most important skills a beginner can build.

When things go wrong — and how to handle it

Every program encounters errors: a user types something unexpected, a network request fails, a file doesn't exist. Without error handling, a single problem crashes the entire program. try/catch lets you catch errors and handle them gracefully — show a helpful message, try something else, or at least log what went wrong.

Reading a JavaScript error

Before you can handle errors, you need to read them. Open your browser console — every error has three key pieces:

// Uncaught TypeError: Cannot read properties of undefined (reading 'name')
//         ↑ type         ↑ what happened                        ↑ detail
//     at getUserName (app.js:12)
//     at main (app.js:25)
//         ↑ stack trace — where in your code it happened

The type tells you what category of error it is. The message tells you what went wrong. The stack trace tells you exactly which line caused it.

try / catch — catch an error and handle it

try {
  // Code that might fail goes here
  const data = JSON.parse("this is not valid JSON");
  console.log(data.name);
} catch (error) {
  // If anything in try throws an error, execution jumps here
  console.error("Something went wrong:", error.message);
  // The program continues normally after the catch block
}

console.log("Program keeps running");

How it works:

  • JavaScript runs the code inside try { }
  • If an error occurs, it immediately jumps to catch — no further lines in try run
  • The error variable holds the Error object with .message and .name
  • After catch, the program continues normally

finally — code that always runs

function readFile(filename) {
  console.log("Opening file...");
  try {
    // Imagine this could fail:
    if (!filename.endsWith(".txt")) {
      throw new Error("Only .txt files are supported");
    }
    console.log("File read successfully");
    return "file contents";
  } catch (error) {
    console.error("Error:", error.message);
    return null;
  } finally {
    // This ALWAYS runs — whether try succeeded or catch ran
    console.log("Closing file... (always happens)");
  }
}

readFile("notes.txt");   // succeeds — finally still runs
readFile("image.png");   // fails — finally still runs

throw — create your own errors

function setAge(age) {
  if (typeof age !== "number") {
    throw new TypeError("Age must be a number");
  }
  if (age < 0 || age > 150) {
    throw new RangeError(`Age ${age} is not a valid age`);
  }
  return age;
}

try {
  setAge("thirty");  // throws TypeError
} catch (e) {
  console.error(e.name + ":", e.message);
  // "TypeError: Age must be a number"
}

try {
  setAge(200);       // throws RangeError
} catch (e) {
  console.error(e.name + ":", e.message);
  // "RangeError: Age 200 is not a valid age"
}

The built-in Error types

TypeError
Wrong type used. Most common: accessing a property on null or undefined.
null.name "abc".sort()
ReferenceError
Using a variable that doesn't exist in scope.
console.log(x) before declaring x
SyntaxError
Code that JavaScript can't parse. Usually a typo.
Missing bracket, wrong quote
RangeError
A number is outside an allowed range.
new Array(-1)
URIError
Malformed URI in decodeURI or encodeURI.
decodeURI("%")
EvalError
Historical — rarely seen in practice today.
Legacy eval() issues
Try It Yourself

Official Sources

The Codex links only to official documentation and the ECMAScript specification. No third-party tutorials.