JavaScript Fundamentals / Error Handling

try, catch, finally

✅ What is try...catch?

try...catch is a built-in error handling mechanism in JavaScript. It allows you to write code that may throw an error, and then catch and handle that error without crashing the application.


🧱 Syntax

try {
  // Code that might throw an error
} catch (error) {
  // Code to handle the error
}

⚙️ How it Works

  1. The code inside the try block is executed.

  2. If there’s an error, the rest of the try block is skipped.

  3. The catch block is executed with the error passed as a parameter.


📌 Example 1: Basic Error Catching

// app.js (Running in Node.js)
try {
  let a = b + 1;  // ❌ b is not defined
} catch (error) {
  console.log("An error occurred:", error.message);
}
An error occurred: b is not defined

📌 Example 2: JSON Parsing

// app.js (Node.js)
try {
  let user = JSON.parse('{"name": "Codeveda"');  // Missing closing brace
} catch (e) {
  console.error("Parsing error:", e.message);
}
Parsing error: Unexpected end of JSON input

🧪 Example 3: Catching TypeError

// app.js (Node.js)
try {
  null.f();  // ❌ Cannot call function on null
} catch (err) {
  console.error("Error Type:", err.name); // TypeError
  console.error("Message:", err.message);
}
Error Type: TypeError
Message: Cannot read properties of null (reading 'f')

✅ What is finally?

The finally block always runs — whether an error was thrown or not. It is useful for cleanup logic like closing files, releasing resources, or ending a loading spinner.


🧱 Syntax with finally

try {
  // Code that might throw
} catch (error) {
  // Handle the error
} finally {
  // Code that always runs
}

📌 Example 4: try...catch...finally

try {
  console.log("Start");
  let result = 10 / 0;
  console.log("Result:", result);
} catch (error) {
  console.error("Error caught:", error.message);
} finally {
  console.log("This always runs.");
}
Start
Result: Infinity
This always runs.

Even though no error is thrown here, finally still runs.


📌 Example 5: Error with finally

try {
  throw new Error("Manual error");
} catch (e) {
  console.log("Caught:", e.message);
} finally {
  console.log("Cleaning up...");
}
Caught: Manual error
Cleaning up...

✅ When to Use

Scenario

Use try...catch?

Use finally?

Invalid JSON parsing

✅

❌

External API call

✅

✅ (cleanup/loading spinner)

File I/O or DB operations

✅

✅

User input validation

✅

❌ (often better to use conditional checks)


❗Important Notes

  • Only runtime errors are caught. Syntax errors won't be caught because the script won't run at all.

  • Works only in synchronous code, unless you're using async/await inside try.


📌 Example 6: Async + try...catch

async function fetchData() {
  try {
    const res = await fetch('<https://api.example.com/data>');
    const data = await res.json();
    console.log(data);
  } catch (error) {
    console.error("Fetch failed:", error.message);
  } finally {
    console.log("Fetch attempt completed.");
  }
}

If Api fails to fetch data

Fetch failed: Failed to fetch
Fetch attempt completed.

📋 Summary

Block

Purpose

try

Run code that might throw an error

catch

Handle any error thrown in the try block

finally

Code that always runs (cleanup/logs/etc.)