How to use try, catch, and finally in JavaScript

· Category: JavaScript

Short answer

Wrap risky code in a try block. If an error is thrown, control jumps to catch. The finally block runs regardless of whether an error occurred.

Steps

  1. Basic structure: javascript try { riskyOperation(); } catch (err) { console.error("Error:", err.message); } finally { console.log("Cleanup"); }
  2. Catch specific error types: javascript try { JSON.parse(input); } catch (err) { if (err instanceof SyntaxError) { console.error("Invalid JSON"); } else { throw err; } }
  3. Use finally for resource cleanup: javascript const file = openFile(); try { process(file); } finally { file.close(); }

Tips

  • Re-throw errors after logging if upstream code should handle them.
  • Use custom error classes to distinguish domain-specific failures.

Common issues

  • Swallowing errors silently in catch blocks makes debugging impossible.
  • finally executes even if try or catch contains a return statement.