JS CodeLab

JavaScript Error Handling Guide: try, catch, finally & throw

By JS CodeLab Engineering Team•Last updated: October 12, 2026•5 min read

Direct Answer & Key Concept

Error handling in JavaScript allows developers to anticipate runtime exceptions, intercept errors gracefully using try...catch...finally blocks, and throw custom Error instances without crashing the application.

Runnable Code SnippetRun in Playground
// Robust Error Handling Example
function safeJsonParse(jsonString, fallback = {}) {
  try {
    return JSON.parse(jsonString);
  } catch (error) {
    console.warn("JSON Parse Warning:", error.message);
    return fallback;
  } finally {
    console.log("Parse attempt completed");
  }
}

const valid = safeJsonParse('{"user": "Alex"}');
console.log("Valid:", valid); // { user: "Alex" }

const invalid = safeJsonParse('Invalid { JSON }', { default: true });
console.log("Fallback:", invalid); // { default: true }

What is Error Handling in JavaScript?

Runtime errors occur when valid code encounters unexpected conditions—such as invalid JSON payloads, network connection drops, or operations on null properties. Without defensive error handling, an uncaught exception halts script execution and destabilizes the web application.

JavaScript provides structured exception handling via the try...catch...finally statement and the throw keyword.


The try, catch, and finally Anatomy

try {
  // Code that might throw an exception
  const data = JSON.parse(rawUserInput);
  processData(data);
} catch (error) {
  // Executed only if an exception was thrown in the try block
  console.error("Parsing failed:", error.message);
} finally {
  // Always executed regardless of whether an error occurred
  cleanupResources();
}

1. The try Block

Encloses code that carries a risk of runtime failure. If no exceptions occur, the catch block is completely bypassed.

2. The catch Block

Catches thrown errors. In modern JavaScript (ES2019+), optional catch binding allows omitting the error parameter if it is not needed: catch { ... }.

3. The finally Block

Guaranteed to execute regardless of whether the try block completed cleanly or threw an error, making it ideal for closing database connections, stopping loading spinners, or clearing file handles.


Throwing Custom Errors

You can create and throw custom exceptions using the built-in Error constructor:

function calculateDiscount(price, percentage) {
  if (typeof price !== "number" || price < 0) {
    throw new TypeError("Price must be a positive number");
  }
  if (percentage < 0 || percentage > 100) {
    throw new RangeError("Percentage must be between 0 and 100");
  }
  return price * (1 - percentage / 100);
}

Standard JavaScript built-in error types include TypeError, RangeError, SyntaxError, and ReferenceError.

Frequently Asked Questions About JavaScript Error Handling: try, catch, finally & throw

What is the purpose of the finally block in JavaScript?

The finally block always executes after try and catch blocks finish, regardless of whether an error was thrown or caught. It is used for cleanup tasks like stopping spinners or closing connections.

Can you rethrow an error inside a catch block?

Yes. If a catch block cannot adequately resolve an exception, it can rethrow the error using throw error so that higher-level caller functions can handle it.

How do you handle errors in asynchronous Promise chains?

In Promise chains, attach a .catch() handler at the end of the chain. In async/await functions, wrap the awaited calls inside a standard try/catch block.

Related Runnable JavaScript Examples

Ready to test what you learned?

The best way to solidify your JavaScript skills is by writing and running code. Open our free online compiler and test your scripts with real-time console feedback.

Open JavaScript Compiler