JavaScript Error Handling

try...catch

Use try...catch to handle exceptions gracefully:

try {
  let result = riskyFunction();
  console.log(result);
} catch (error) {
  console.error("An error occurred:", error);
}

The code in catch only runs if an error occurs in try.

The Error Object

The caught error is usually an instance of the Error object, with helpful info:

try {
  throw new Error("Something went wrong");
} catch (e) {
  console.log(e.message);  // Something went wrong
  console.log(e.name);     // Error
}

finally Block

The finally block runs whether or not an error was thrown:

try {
  // some code
} catch (e) {
  // error handling
} finally {
  console.log("Always runs");
}

Useful for closing connections, clearing timers, etc.

Throwing Custom Errors

You can use throw to manually raise an error:

function checkAge(age) {
  if (age < 18) {
    throw new Error("User must be at least 18");
  }
  return true;
}

try {
  checkAge(15);
} catch (e) {
  alert(e.message);
}

Practical Examples

  • Try/catch for JSON parsing:
try {
  const user = JSON.parse('{ bad json }');
} catch (e) {
  console.log("Invalid JSON!");
}
  • Network or API request error catching
  • Form validation and exception throwing

Best Practices

  • Use meaningful error messages
  • Don’t silently suppress errors without logging
  • Use finally to release resources regardless of errors

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic