Use try...catch to handle exceptions gracefully:
try {
let result = riskyFunction();
console.log(result);
} catch (error) {
console.error("An error occurred:", error);
}The code in catch only runs if an error occurs in try.
The caught error is usually an instance of the Error object, with helpful info:
try {
throw new Error("Something went wrong");
} catch (e) {
console.log(e.message); // Something went wrong
console.log(e.name); // Error
}The finally block runs whether or not an error was thrown:
try {
// some code
} catch (e) {
// error handling
} finally {
console.log("Always runs");
}Useful for closing connections, clearing timers, etc.
You can use throw to manually raise an error:
function checkAge(age) {
if (age < 18) {
throw new Error("User must be at least 18");
}
return true;
}
try {
checkAge(15);
} catch (e) {
alert(e.message);
}try {
const user = JSON.parse('{ bad json }');
} catch (e) {
console.log("Invalid JSON!");
}finally to release resources regardless of errorsAsk the AI if you need help understanding or want to dive deeper in any topic