JavaScript Interview Question #143
What is error handling with try, catch, and finally?
Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced
Quick Interview Answer
The try block contains code that may throw. If an exception is thrown, control moves to the matching catch block. The optional finally block runs after try/catch processing whether an error occurred or not, making it useful for cleanup.
Detailed Explanation
The try block contains code that may throw. If an exception is thrown, control moves to the matching catch block. The optional finally block runs after try/catch processing whether an error occurred or not, making it useful for cleanup.
Errors should normally be handled at a layer that can make a meaningful decision, such as retrying, displaying a message, translating the error, or recording diagnostic information. Catching an error only to ignore it can hide failures.
Code Example
try {
const data = JSON.parse(input);
console.log(data);
} catch (error) {
console.error("Invalid JSON:", error.message);
} finally {
console.log("Parsing attempt finished");
}