🚀 LEVEL UP TO SENIOR:Unlock 500+ Advanced Practical Challenges & Exercises.
🎓 COURSERA PARTNER:Earn professional Google, Meta, and IBM certificates to supercharge your resume.
REFERENCEjavascript

javascript Documentation

LOADING ENGINE...

try...catch

AI & DATA SCIENCE // trycatch

try...catch handles exceptions: code that might throw runs in try; if an error occurs, catch handles it gracefully.

Syntax

try {
  riskyOperation();
} catch (error) {
  console.error(error.message);
} finally {
  cleanup();
}

Deep Dive Course

**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.

editor.html
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
localhost:3000

2Practical Example

Here is a real-world application of try...catch showing how it is used in production JavaScript code.

editor.html
// 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;
  }
}
localhost:3000

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.

editor.html
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
localhost:3000

Examples

Example 01Basic Usage
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
Example 02Advanced Example
// 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;
  }
}

Best Practices

  • Log the error in catch for debugging
  • Re-throw errors you can't handle at that level
  • Use finally for cleanup (close connections, hide spinners)

Interview Question

When should you re-throw an error instead of catching it?

Hint: Catch what you can handle; rethrow the rest.

Re-throw when you can't meaningfully handle an error at the current level. Example: you catch a network error to log it, but re-throw it so the UI layer can show a user-facing error message. Only catch errors at the level that can do something useful with them.

Exercises

MediumPractice using try...catch in a real scenario.
View Solution
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

Frequently Asked Questions

When should you re-throw an error instead of catching it?

Re-throw when you can't meaningfully handle an error at the current level. Example: you catch a network error to log it, but re-throw it so the UI layer can show a user-facing error message. Only catch errors at the level that can do something useful with them.

Related Functions

throwfinallyError-ObjectsCustom-ExceptionsPromises