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
- Basic structure:
javascript try { riskyOperation(); } catch (err) { console.error("Error:", err.message); } finally { console.log("Cleanup"); } - Catch specific error types:
javascript try { JSON.parse(input); } catch (err) { if (err instanceof SyntaxError) { console.error("Invalid JSON"); } else { throw err; } } - Use
finallyfor 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.
finallyexecutes even iftryorcatchcontains areturnstatement.