**try...catch** prevents uncaught errors from crashing your program. Code in the **try** block runs; if any line throws, JavaScript jumps to **catch** with the Error object. **finally** always runs (cleanup, closing connections). Errors in async code require try/catch inside `async` functions or `.catch()` on Promises.
1Understanding try...catch
try...catch prevents uncaught errors from crashing your program. Code in the try block runs; if any line throws, JavaScript jumps to catch with the Error object. finally always runs (cleanup, closing connections). Errors in async code require try/catch inside async functions or .catch() on Promises.
Only catch errors you can handle meaningfully. Catching and swallowing all errors hides bugs.
function parseJSON(str) {
try {
return JSON.parse(str);
} catch (e) {
console.error('Invalid JSON:', e.message);
return null;
}
}
console.log(parseJSON('{"name":"Alice"}')); // { name: 'Alice' }
console.log(parseJSON('not json')); // null2Practical Example
Here is a real-world application of try...catch showing how it is used in production JavaScript code.
// Async error handling
async function fetchUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return await res.json();
} catch (e) {
console.error('Failed to fetch user:', e.message);
return null;
}
}3Best Practices
Follow these guidelines when working with try...catch:
1. Log the error in catch for debugging
2. Re-throw errors you can't handle at that level
3. Use finally for cleanup (close connections, hide spinners)
Tip: Only catch errors you can handle meaningfully. Catching and swallowing all errors hides bugs.
function parseJSON(str) {
try {
return JSON.parse(str);
} catch (e) {
console.error('Invalid JSON:', e.message);
return null;
}
}
console.log(parseJSON('{"name":"Alice"}')); // { name: 'Alice' }
console.log(parseJSON('not json')); // null