← Back to JavaScript Course | Chapter 8: Error Handling | Lesson 2 of 6

JS try catch finally

The try Block

Code placed inside a try block runs normally until (and unless) it throws; if nothing throws, the catch block is skipped entirely and execution continues after it.

Example: The try Block

javascript
try {
  console.log("This runs");
} catch (e) {
  console.log("Skipped, nothing threw");
}

The catch Block

The catch block receives the thrown value as its parameter and runs only when the try block throws, letting you inspect the error, decide how to respond, and optionally recover instead of letting it propagate further.

Example: The catch Block

javascript
try {
  null.name;
} catch (error) {
  console.log("Caught:", error.message);
}

The finally Block

The finally block runs after try/catch regardless of whether an error was thrown or caught, making it the right place for cleanup code like closing a file or resetting UI state.

Example: The finally Block

javascript
try {
  console.log("try");
} finally {
  console.log("finally always runs");
}

Return with try catch finally

A return inside try is deferred until after finally runs; if finally also returns a value, that finally return silently overrides the one from try — a subtle gotcha worth knowing.

Example: Return with try catch finally

javascript
function test() {
  try {
    return "from try";
  } finally {
    return "from finally"; // overrides the try's return
  }
}
console.log(test());

Nested try catch

try/catch blocks can be nested, letting an inner block handle a specific, recoverable failure while an outer block catches anything more serious that escapes the inner one.

Example: Nested try catch

javascript
try {
  try {
    throw new Error("inner failure");
  } catch (inner) {
    console.log("Handled inner:", inner.message);
  }
} catch (outer) {
  console.log("Handled outer:", outer.message);
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.