How does a try/catch block work?
Short 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.
Advertisement
AModel 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.
Likely follow-ups
- What runs if there's no error at all — does catch still execute?
Related topics