throw and try/catch

JavaScript uses exceptions for abrupt control flow. throw can throw any value, although throwing an Error object is strongly preferred because it provides a stack trace and standardized error metadata. try/catch intercepts exceptions thrown during execution of the protected block.

Catch blocks should add useful context or recover when appropriate rather than blindly swallowing failures.

Catching an Error
function parseUser(input) {
  try {
    return JSON.parse(input);
  } catch (error) {
    throw new Error('Invalid user payload', { cause: error });
  }
}

try {
  parseUser('{invalid}');
} catch (error) {
  console.error(error.message);
  console.error(error.cause);
}
💡 The original parsing failure is preserved as the cause of a more domain-specific error.
Key Takeaways
  • Prefer throwing Error objects.
  • Use catch blocks to recover or add meaningful context.
  • Error causes can preserve the original failure.
Knowledge Check

What is generally the best thing to throw for an application error?