JavaScript › Error Handling

How does a try/catch block work?

Beginner

Answer

Code inside try runs normally; if it throws an error, execution immediately jumps to the catch block instead of crashing the whole program, letting you handle the error gracefully.
try {
  JSON.parse('not valid json');
} catch (err) {
  console.log('Failed to parse:', err.message);
}
Real-world example Safely parsing user-provided JSON input without crashing the app on malformed data.

Common follow-ups: What runs if there's no error at all — does catch still execute?