Introduction
Try-catch helps you catch and handle errors that happen while your code runs, so your program doesn't crash unexpectedly.
Jump into concepts and practice - no test required
try {
// code that might throw an error
} catch (error) {
// code to handle the error
}try runs normally unless an error happens.catch runs with the error details.catch won't run.try { let result = 10 / 0; console.log(result); } catch (error) { console.log('Error caught:', error.message); }
catch.try { JSON.parse('invalid json'); } catch (error) { console.log('Parsing failed:', error.message); }
catch.try { nonExistentFunction(); } catch (error) { console.log('Function error:', error.message); }
try { const data = JSON.parse('{"name": "Alice"}'); console.log('Name:', data.name); const brokenData = JSON.parse('bad json'); console.log('This line will not run'); } catch (error) { console.log('Caught an error:', error.message); } console.log('Program continues running');
try-catch in Node.js?try { ... } catch (error) { ... } with parentheses around the error variable.try {
throw new Error('Oops!');
console.log('This will not run');
} catch (e) {
console.log('Caught:', e.message);
}try {
console.log('Start');
throw 'Error happened';
} catch e {
console.log('Caught:', e);
}catch (e).null if parsing fails?