try...catch...finally
The core JavaScript construct for catching runtime errors so a script doesn't crash.
try {
const data = JSON.parse(invalidJson);
} catch (error) {
console.error('Parsing failed:', error.message);
} finally {
console.log('Always runs, error or not');
}
- try holds code that might throw
- catch runs only if an error was thrown, receiving the Error object
- finally always runs — great for cleanup like closing a connection
- try/catch does NOT catch errors inside setTimeout or Promise callbacks unless you await/catch them there too