Error handling in JavaScript is crucial for writing robust and reliable code. JavaScript provides several mechanisms for handling errors and exceptions. Here's an overview:
Try...Catch Statement: The try...catch statement allows you to catch and handle exceptions that occur within a block of code.
JavaScript code:
try {
// Code that may throw an exception
throw new Error("Something went wrong");
} catch (error) {
// Handle the exception
console.error("An error occurred:", error.message);
}
Throw Statement: You can throw your own exceptions using the throw statement. This is useful for signaling errors or exceptional conditions in your code.
JavaScript code:
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero");
}
return a / b;
}
Error Object: JavaScript provides built-in error objects like Error, SyntaxError, ReferenceError, TypeError, etc., which can be thrown or caught.
JavaScript code:
try {
// Code that may throw a TypeError
undefinedVariable.foo();
} catch (error) {
if (error instanceof TypeError) {
console.error("TypeError:", error.message);
} else {
console.error("An error occurred:", error.message);
}
}
Finally Block: You can use the finally block to execute code regardless of whether an exception is thrown or not. This block is optional and follows the catch block.
JavaScript code:
try {
// Code that may throw an exception
throw new Error("Something went wrong");
} catch (error) {
// Handle the exception
console.error("An error occurred:", error.message);
} finally {
// Code that always runs
console.log("Cleanup code");
}
Global Error Handling: You can also set up a global error handler using the window.onerror event handler or the window.addEventListener('error', handler) method to catch unhandled errors.
JavaScript code
window.onerror = function(message, source, lineno, colno, error) {
console.error("Unhandled error:", message);
};
By using these error handling techniques effectively, you can make your JavaScript code more resilient and easier to debug.
Thank you for watching this video
EVERYDAY BE CODING
![](https://s2.save4k.ru/pic/qJKJw8qavZc/maxresdefault.jpg)