When executing JavaScript code, different errors can occur. Error handling allows you to test your code for errors, catch them when they happen, and handle them gracefully so your program doesn't crash.
The try statement allows you to define a block of code to be
tested for errors while it is being executed. The catch
statement allows you to define a block of code to be executed, if an error occurs in the try
block.
try {
// Block of code to try
adddlert("Welcome guest!"); // Error: adddlert is not defined
}
catch(err) {
// Block of code to handle errors
console.log(err.message); // Displays the error message
}
The throw statement allows you to create a custom error.
Technically you can throw anything (a string, a number, a boolean, or an object), but it is
best practice to throw an Error object.
function checkAge(age) {
if (age < 18) throw "Too young!";
if (age > 100) throw new Error("Age is unrealistic");
}
The finally statement defines a block of code to be executed
regardless of the result (whether an error was caught or not). It is
perfect for cleanup tasks like closing files or stopping loading animations.
try to wrap risky codecatch to manage the fallout without crashingthrow lets you control the "bad" logic in your own app
finally always runs—perfect for "cleaning up"name and message
for debugging