try, catch, finally
try/catch/finally is the standard way to handle errors in JavaScript. The try block contains code that might fail, catch handles the error, and finally runs cleanup code regardless of success or failure.
try/catch/finally
- try { } — Wrap code that might throw an error
- catch (error) { } — Handles the error. Has access to the error object
- finally { } — Always runs (success or failure). For cleanup: close connections, hide loaders
- Only catch what you can handle — Re-throw errors you can't handle: throw error
- Nesting — try/catch can be nested. Inner catch handles inner errors
- Performance — try/catch has minimal overhead. Don't avoid it for 'performance'
try/catch/finally Code
// Basic try/catch
try {
const data = JSON.parse('{"name": "Alice"}');
console.log("Parsed:", data.name);
} catch (error) {
console.error("Parse error:", error.message);
}
// try/catch/finally
function fetchData() {
let loading = true;
console.log("⏳ Loading...");
try {
// Simulate potential errors
const result = JSON.parse('{"status": "ok"}');
console.log("✅ Data:", result);
} catch (error) {
console.error("❌ Error:", error.message);
} finally {
loading = false;
console.log("🔄 Cleanup: loading =", loading);
// Finally ALWAYS runs — perfect for cleanup
}
}
fetchData();
// Selective error handling
function processInput(input) {
try {
if (typeof input !== "string") {
throw new TypeError("Input must be a string");
}
const data = JSON.parse(input);
return data;
} catch (error) {
if (error instanceof TypeError) {
console.error("Type error:", error.message);
return null;
}
if (error instanceof SyntaxError) {
console.error("Invalid JSON:", error.message);
return null;
}
throw error; // re-throw unexpected errors
}
}
processInput(42); // Type error: Input must be a string
processInput("{invalid}"); // Invalid JSON
processInput('{"ok":true}'); // SuccessTip
Tip
Use finally for cleanup code that must run regardless of success or failure: closing connections, hiding spinners, re-enabling buttons. try { await fetch() } catch(e) { showError() } finally { hideSpinner() }.
Never swallow errors silently. Log, report, recover gracefully.
Common Mistake
Warning
Wrapping too much code in try/catch. Only wrap the specific operation that might fail, not your entire function. Over-catching hides bugs and makes debugging harder. Be surgical with try blocks.
Practice Task
Note
Error handling: (1) Write a function that parses JSON with try/catch and returns a default on failure. (2) Create a retry wrapper that attempts an operation 3 times. (3) Chain multiple try/catch for different error scenarios.
Quick Quiz
Key Takeaways
- try/catch/finally is the standard way to handle errors in JavaScript.
- try { } — Wrap code that might throw an error
- catch (error) { } — Handles the error. Has access to the error object
- finally { } — Always runs (success or failure). For cleanup: close connections, hide loaders