Error Handling

</>Coding Tamilan.← JavaScript course

JavaScript · Lesson 25 / 32 · English

Error Handling

Understand the idea. Change the code. Build confidence with one focused experiment.

Detailed notesRunnable JavaScriptPractice + answer

Read this lesson in தமிழ் ↗.

01 / Understand

Start with the idea

Errors describe failed operations. Catch errors where you can recover or add useful context; do not silently discard them. finally runs after try/catch for cleanup.

Learning goal: Explain what the example does, predict its result, and change it to solve the practice task.

02 / Explore

Step-by-step lesson notes

Error Handling in JavaScript

Errors are inevitable. Good error handling prevents your app from crashing and gives users meaningful feedback.

try / catch / finally

JavaScript reference fragmentCODE
try {
  // Code that might throw
  const data = JSON.parse("invalid json");
  console.log(data);
} catch (error) {
  console.error("Error:", error.message);
  console.error("Type:", error.name); // "SyntaxError"
} finally {
  // Always runs — for cleanup
  console.log("Done.");
}

// Optional catch binding (ES2019)
try {
  riskyOperation();
} catch {
  console.log("Something went wrong");
}

Error Types

Error TypeWhen it occurs
SyntaxErrorInvalid JavaScript syntax (parsing)
ReferenceErrorUsing an undeclared variable
TypeErrorWrong type (e.g., calling non-function)
RangeErrorValue out of valid range
URIErrorInvalid URI encoding/decoding
EvalErrorError with eval() function

Throwing Custom Errors

JavaScript reference fragmentCODE
// Throw built-in error
throw new Error("Something went wrong");
throw new TypeError("Expected a string");

// Custom error class
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "ValidationError";
    this.field = field;
  }
}

function validateAge(age) {
  if (typeof age !== "number") {
    throw new ValidationError("Age must be a number", "age");
  }
  if (age < 0 || age > 150) {
    throw new ValidationError("Age must be between 0 and 150", "age");
  }
  return true;
}

try {
  validateAge("old");
} catch (err) {
  if (err instanceof ValidationError) {
    console.log(`Field: ${err.field} — ${err.message}`);
  } else {
    throw err; // re-throw unexpected errors
  }
}
03 / Read & predict

A complete example

Run this complete index.js program in the JavaScript console editor below. The earlier reference fragments may need a browser page or other surrounding setup.

index.js · complete exampleCODE
try {
  JSON.parse("not valid JSON");
} catch (error) {
  console.log(error.name);
} finally {
  console.log("Finished checking");
}
Predict first. Reveal the expected result.
SyntaxError
Finished checking
04 / Experiment

Make one change. See what happens.

Load the example, change a value, predict the output, and run it again. Use the console output to check your reasoning.

Open editor ↗

Wait for the editor to load, then load this example and press Run.

Powered by the free OneCompiler editor. Code you run is sent to that external service. Keep personal data and secret keys out of your examples.

05 / Your turn

Put the idea to work

Practice challenge

Replace the input with valid JSON and log the parsed title.

Reveal the answer and reasoning

Parse '{"title":"JavaScript"}' and log .title. The catch block is skipped; finally still runs.

One mistake to avoid: A synchronous try/catch does not catch a later rejected promise unless that promise is awaited inside the try block.

Your learning checkpoint

  • Explain the example in your own words.
  • Complete the challenge before revealing its answer.
  • Describe the common mistake and how to avoid it.
Coding Tamilan · Learn by doing.